Following on from my last post I've been migrating more services into EC2 from my current hosting provider. Another task I found myself needing to do was creating swap files for my EC2 instances. This was another task for which I had completely forgotten the step.

For my use case, I needed to create a 1GiB swap file. To create the file I first tried to use fallocate:

$ fallocate -l 1G /mnt/swapfile

I found out later that on XFS fallocate has some issues creating files without holes/gaps, so these files don't work as swap files. Instead, I used dd:

$ dd if=/dev/zero of=/mnt/swapfile bs=1MiB count=1024

This will create a 1024MiB (or 1 GiB) file at /mnt/swapfile. The next step is to set the correct permissions:

$ chmod 600 /mnt/swapfile

Then, we format the file as a swap file:

$ mkswap /mnt/swapfile

After this we can mount it as swap!

$ swapon /mnt/swapfile

We can verify that the swap has been added successfully using swapon -s which produces something like:

Filename                                Type            Size    Used    Priority
/mnt/swapfile                           file    1048572 0       -1

The final step is to ensure that the swap is added on boot. To do this we need to add an entry to /etc/fstab:

/mnt/swapfile   none    swap    sw              0   0

With that in place, the swap will be added after each reboot so you won't need to manually run swapon every time.

Creating Linux swap files