linux add swap file on the fly

htop cpu memory swap

Some hosters provide VPS / cloud servers without a swapfile , many time it is usefull to have one to avoid possible “no-RAM kill approach” , first step add a file ( possibly the same dimension of the RAM attached )

fallocate -l 1G /swapfile

if fallocate is not available , just install or instead you can use the old but gold “dd

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

Now let’s start to manage the swap file first fix privileges :

chmod 600 /swapfile

second format the file

mkswap /swapfile

third attach it in the system

swapon /swapfile

now the SWAP is added and ready , now to make it persistent must be added in the filesystem tab configuration file ( /etc/fstab )

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

im my humble opinion a swappiness of 10 is a good starting point . swappiness is how often the system move data from RAM to SWAP.
edit the sysctl conf

YOUR_EDITOR /etc/sysctl.conf

change or add :

vm.swappiness=10

If you know what you are going to do you can copy and paste the whole set of commands

fallocate -l 1G /swapfile ;
chmod 600 /swapfile ;
mkswap /swapfile ;
swapon /swapfile ;
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Torna in alto