Skip to content

Instantly share code, notes, and snippets.

@vaughany
Created March 6, 2020 14:03
Show Gist options
  • Select an option

  • Save vaughany/1f576b1420a5fa26f6d812ff4182b620 to your computer and use it in GitHub Desktop.

Select an option

Save vaughany/1f576b1420a5fa26f6d812ff4182b620 to your computer and use it in GitHub Desktop.
Configuring swap files and swapiness.

Swap file creation, use and deletion

Info

$ free -h
              total        used        free      shared  buff/cache   available
Mem:            31G        3.8G        7.1G        1.2G         20G         25G
Swap:          979M          0B        979M
$ swapon --show
NAME      TYPE      SIZE USED PRIO
/dev/dm-2 partition 980M   0B   -2

Creating a New Swap File

If you want to add 2GB or more instead of 1 GB, replace 1G with 2G, 3G, 4G etc.

Create a file that will be used for swap:

$ sudo fallocate -l 1G /swapfile

...or:

$ sudo dd if=/dev/zero of=/swapfile bs=1024 count=1048576

Set root permissions:

$ sudo chmod 600 /swapfile

Use the mkswap command to set up the file as a swap area:

$ sudo mkswap /swapfile

Enable the new swap file:

$ sudo swapon /swapfile

To make the change permanent across reboots), open /etc/fstab and add the following line:

$ sudo nano /etc/fstab
/swapfile swap swap defaults 0 0

To verify that the swap is active:

$ swapon --show
NAME      TYPE      SIZE  USED PRIO
/dev/dm-2 partition 980M    0B   -2
/swapfile file      1024M   0B   -3
$ free -h
              total        used        free      shared  buff/cache   available
Mem:            31G        3.8G        7.1G        1.2G         20G         25G
Swap:          1.9G        0B          1.9G

Removing a Swap File

First, deactivate the swap by typing (-v stands for 'verbose'):

$ sudo swapoff -v /swapfile

If added, remove the swap file entry from /etc/fstab:

$ sudo nano /etc/fstab
/swapfile swap swap defaults 0 0

Delete the actual swap file file using the rm command:

$ sudo rm /swapfile

Changing 'Swappiness'

Check the current swappiness value (60 is the default):

$ cat /proc/sys/vm/swappiness
60

Set the swappiness value to 40:

$ sudo sysctl vm.swappiness=40

$ cat /proc/sys/vm/swappiness
40

To make the change permanent across reboots, open /etc/sysctl.conf and add the following line:

$ sudo nano /etc/sysctl.conf
vm.swappiness=10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment