Adding a Swap File to CentOS

Memory on desktop PC has been a solved problem for a while now. You have certain quantity of it and you rarely really run out of it. Even when you do, there is a virtual memory to soften the blow at the cost of performance. Enter the cloud...

When you deal with mini virtual machines running on a cloud, quite often they have modest memory specification - 1 GB or even less are the usual starting point. Fortunately, they run on Linux so they don't need much memory - except when they do.

What to do if you need just a bit more memory on already configured machine and you really don't want to deal with reboots required for proper upscaling? Well, you can always add a swap file.

First, you create a file (I'll call mine Swapfile.sys for sentimental reasons) with the additional 1 GB (or whatever value you want):

Terminal
dd if=/dev/zero of=/swapfile.sys bs=1M count=1024
chmod 600 /swapfile.sys

Then you format this file as a swap and tell the system to use it:

Terminal
mkswap /swapfile.sys
swapon /swapfile.sys

Since this disappears upon reboot, you might also want to make it permanent by adding it to fstab. This step is a bit controversial since you should really think about bigger machine if you are always in need of the extra memory:

Terminal
sed -i '$ a\/swapfile.sys\tnone\tswap\tsw\t0\t0' /etc/fstab

That's it. A bit of room to breathe.

Leave a Reply

Your email address will not be published. Required fields are marked *