Swap is a file on a hard drive to provide temporary storage space to use instead of RAM when the system has low memory. Creating a swap file on a VPS is recommended even if you already have plenty of RAM. Sometimes, legacy software needs it. However, you can’t configure a swap file or partition on OpenVZ unless it’s already provided in the template. This tutorial will show you how to create a swap file on Debian 11, but it can be applied to other Linux distros as well.
Checking if there is a swap file already activated
Check if your system already has a swap file using the
free -h command. If you installed the OS using a template from your VPS provider, you may already have a swap partition enabled.
If not, the
Swap section will be displayed as
0B like so.
total used free shared buff/cache available Mem: 1.9Gi 526Mi 964Mi 56Mi 492Mi 1.2Gi Swap: 0B 0B 0B
Creating a swap file
Create a swap file using
dd with the following command. Feel free to change
count=512 to the file size you prefer in MB, such as
count=1024 for a 1GB swap file. If you have less than 1 GB RAM, it’s recommended to have a 1 or 2 GB maximum swap file. I’ll create a 512 MB swap file in this tutorial.
sudo dd if=/dev/zero of=/swapfile bs=1M count=512 status=progress
Change the chmod of the swap file to 600 to make it readable and writable to the system only.
sudo chmod 600 /swapfile
Format the swap file to swap properly using the
sudo mkswap /swapfile
Activate the swap file using the
sudo swapon /swapfile
Editing the fstab file
You have to edit the fstab file located at
/etc/fstab to mount the swap file to the system when booting.
sudo vi /etc/fstab
Append the following line to the fstab file. Save changes and exit.
/swapfile none swap sw 0 0
Checking if the swap file is activated
Check if the swap file is activated using the
free -h command. If you did it correctly, the
Swap section will be displayed like so.
total used free shared buff/cache available Mem: 1.9Gi 526Mi 962Mi 56Mi 494Mi 1.2Gi Swap: 511Mi 0B 511Mi
Editing the sysctl.conf file
Open the sysctl.conf file location at
/etc/sysctl.conf. It’s recommended to set the
vm.swappines value from the default one to 10 which will help avoid using the swap file when not needed for better performance.
sudo vi /etc/sysctl.conf
Append the following line to the sysctl.conf file. Save changes and exit. Run
sudo sysctl -p to reload the configuration file or reboot the system.
vm.swappiness = 10