Adding a swap file on Linux

At work some of our Red Hat (RHEL5) servers with 32GB of ram were configured with only 2 Gb swap files. For some workloads this might be fine, but a 2-in-1 Apache and MySQL server is not one of them.

Red Hat’s recommendation for RHEL6 is as follows:

If M < 2
	S = M *2
Else
	S = M + 2

Where:

  • M = Amount of RAM in GB
  • S = Amount of swap in GB

Source is here.

What this means is that our server should really have 34Gb of swap space, substantially more than 2Gb, unless the workload was tuned to use only ~16GB of ram, which is certainly not the case.

Fortunately on Linux, swap files are basically as fast as partitions. The only problems are the potential for fragmentation, and the fact that the kernel can't write suspend data to a swap file on a mounted file system. On a server with 50% of its space free, neither of these are issues.

In the past I used dd to make a blank file, e.g.:

dd if=/dev/zero of=./swap.file bs=1M count=10240

The problem is that this is slow - it takes quite a while to write out a 10Gb file to disk, even on a decent raid array. The extra I/O load may also not be desirable on a busy server, and if you're adding an "emergency" swap file as I had to do on this particular machine, speed becomes even more important.

So my new command for the day is fallocate, which allocates the space without having to write out every block:

fallocate -l  

Full syntax here.

The full process for adding a swap file to the server is thus:

sudo fallocate -l 10G /mnt/swapfile.10G
sudo mkswap /mnt/swapfile.10G
sudo swapon /mnt/swapfile.10G

Don't forget to update /etc/fstab!:

/mnt/swapfile.10G none swap sw 0 0

One thought on “Adding a swap file on Linux

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.