Create Swap File on Linux Servers for Better Performance

Are you running a low memory server and your applications are crashing? You can create swap file to prevent your applications from crashing in just 5 minutes.

Low memory servers often crash when there is a sudden spike in workload. However, upgrading your server is not an option (yet) due to budget. Restarting your services or applications is cumbersome and it is not possible to check every second if anything has crashed.

In this article, I will show you how you can create swap file on Linux servers to improve your server’s performance and prevent it from crashing.

What is a swap file?

A swap file is a space on the hard disk used as memory. When your RAM is full, the least recently used files are swapped out to make space. Generally, swap files are twice the size of your RAM. This allows you to swap your entire RAM when needed.

Swap files are important when you are running applications that require a lot memory. Without a swap file, your application will crash when out of memory.

Create swap file

Before we begin, you can check if there is a swap file by running free.

$ free -m

You can create swap file with the following commands. To determine the size of your swap file, multiply the size in megabytes by 1024. For example, 64 MB has a block size of 65536.

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

Next, change the permission and setup the swap file.

$ sudo chmod 600 /swapfile

$ sudo mkswap /swapfile

Finally, enable the swap file you had just created but will not enable it on boot.

$ sudo swapon /swapfile

If you want to enable it on boot, you will need to modify /etc/fstab and include the line below.

/swapfile swap swap defaults 0 0

You can verify if you have correctly enabled the swap file by running free again.

swap file enabled

If you are using PHP, see how you can optimize PHP-FPM on low memory Nginx servers to use lower its memory footprint.

Hope this article helped you learned how to create swap file on Linux servers for better performance.

If you liked this article, please do share this article with your friends and family.