Skip to content

Instantly share code, notes, and snippets.

@jesugmz
Last active October 5, 2020 17:02
Show Gist options
  • Save jesugmz/19325b7fcd09dc3fcb3155b6c018cf39 to your computer and use it in GitHub Desktop.
Save jesugmz/19325b7fcd09dc3fcb3155b6c018cf39 to your computer and use it in GitHub Desktop.
Create and add a swap file in Linux

Create and add a swap file in Linux

1. Create Storage File

Type the following command to create 512MB swap file (1024 * 512MB = 524288 block size):

dd if=/dev/zero of=/swapfile bs=1024 count=524288

2. Secure swap file

chown root:root /swapfile
chmod 0600 /swapfile

3. Set up a Linux swap area

mkswap /swapfile

4. Enabling the swap file

swapon /swapfile

Optional. Persist the changes on system reboot

Open /etc/fstab and append the following line:

/swapfile none swap sw 0 0

To disable it:

swapoff /swapfile && swapon -s

The value in /proc/sys/vm/swappiness file controls how aggressively the kernel will swap memory pages. Higher values increase agressiveness, lower values descrease aggressiveness. The default value is 60. To make changes permanent:

sysctl -w vm.swappiness=VALUE && sysctl -p

Source Linux Add a Swap File – HowTo

@jesugmz
Copy link
Author

jesugmz commented May 19, 2020

CoreOS systemd unit - and for any systemd OS - to execute it at boot time:

$ cat /etc/systemd/system/swap-file.service
[Unit]
Description=Creates swap file

[Service]
Type=oneshot
ExecStart=/usr/bin/sh -c '/home/core/make-swap.sh'

[Install]
WantedBy=multi-user.target

Ensure service activation with sudo systemctl enable swap-file.service.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment