Passer au contenu principal

Create swape file 🇬🇧

Tuto from itsfoss.com and linuxhandbook.com.

Check swap space in Linux

$ free -h
              total        used        free      shared  buff/cache   available
Mem:          1,7Gi       844Mi       321Mi        18Mi       603Mi       759Mi
Swap:            0B          0B          0B

There is no swap space.

Make a new swap file

  1. Use the fallocate command to create a file of size 1 GB.
  2. It is recommended to allow only root to read and write to the swap file.
$ sudo fallocate -l 1G /swapfile
$ sudo chmod 600 /swapfile

The name of the swap file could be anything.

Mark the new file as swap space

$ sudo mkswap /swapfile
Configure l'espace d'échange (swap) en version 1, taille = 1024 MiB (1073737728 octets)
pas d'étiquette, UUID=3bbb4a53-e2a4-495f-8e42-d7cb43e6ad40

Enable the swap file

  1. Enable the swap file.
  2. Check the swap space.
$ sudo swapon /swapfile
$ swapon --show        
NAME      TYPE  SIZE USED PRIO
/swapfile file 1024M   0B   -2

Make the changes permanent

  1. It’s always a good idea to make a backup before make any changes to the /etc/fstab file.
  2. Add the line to the end of /etc/fstab file.
$ sudo cp /etc/fstab /etc/fstab.back

Change Swapiness kernel parameter

Temporary change

Check swapiness:

cat /proc/sys/vm/swappiness

Change setting:

sudo sysctl vm.swappiness=10

Persistent change

Edit the config file:

sudo vim /etc/sysctl.conf

Set swapiness:

# /etc/sysctl.conf
vm.swappiness=10

Reload sysctl:

sudo sysctl -p

[Bonus] Resize swap file

Make sure the swapfile is on the system and not a swap partition.

$ swapon --show                             
NAME      TYPE SIZE USED PRIO
/swapfile file   1G   0B   -2

Now before you resize the swap file, you should turn the swap off.
You should also make sure that you have enough free RAM available to take the data from swap file.
Otherwise, create a temporary swap file.

A solution to clear swapfile is to reboot the system…

Disable the swapfile.

$ sudo swapoff /swapfile

Now, use the fallocate to change the size of the swap file.

$ sudo fallocate -l 2G /swapfile

Mark the file as a swap file.

$ sudo mkswap /swapfile                                             
mkswap: /swapfile : avertissement : effacement de l'ancienne signature swap.
Configure l'espace d'échange (swap) en version 1, taille = 2 GiB (2147479552 octets)
pas d'étiquette, UUID=bf273c02-f44a-48ef-9b04-b212d9003a4a

Enable the swap file.

$ sudo swapon /swapfile 

Check!

$ free -h
              total        used        free      shared  buff/cache   available
Mem:          1,7Gi       1,0Gi       138Mi        65Mi       619Mi       541Mi
Swap:         2,0Gi       0,0Ki       2,0Gi