How to create swap memory for your Linux server

Firstly we’d confirm how much memory you have on your server:

free -m

There’s no definitive rule when it comes to how much swap is enough, but try somewhere between 1-2 times the amount of physical RAM your server has. 1.5 is usually good enough.

Next, aside from confirming how much disk space you have, we’ll create a swap file. This is the way to go if you didn’t partition the HDD (or in my case where I’m on a VM and I didn’t have the opportunity to do so during set up).

sudo dd if=/dev/zero of=[locationOfSwapFile] bs=[sizeOfSwapFile] count=4

Location of Swap File “usually” sits at the root directory, so something like /swapfile is good enough. It clearly explains what the file is for. Size of Swap File is a short code for how big you want the file to be. You can specify the byte size, or provide a short code, such as 1.5GB. Running this command can take some time as it has to create a file with zero’s in it to the exact size you’ve just specified so slow disks will take a while.

Next we’ll set up the appropriate file permissions using:

chmod 600 /swapfile

Then finally we’ll tell Linux that this file is to be used as swap space by issuing:

mkswap /swapfile

At this point the file is ready to use, so let’s enable it by issuing:

swapon /swapfile

You should then be able to confirm it’s live by running:

swapon -s

Or by checking how much memory is available on the system by running:

free -m

If you want the swap file to be mounted automatically, don’t forget to add it to the fstab by editing the file:

vim /etc/fstab

And adding the following line:

/swapfile   none    swap    sw    0   0

Lastly, the swappiness of your system is available by issuing:

cat /proc/sys/vm/swappiness

Tweaking this value depending upon your usage is important. Servers want to swap a little more than desktops so lower values are recommended. You can update your swappiness by issuing:

sysctl vm.swappiness=[newSwappinessValue]

This will only last whilst the server is running. You can permanently update this value by modifying:

/etc/sysctl.conf

And updating the value:

vm.swappiness=[valueOfSwappiness]

Kudos to https://www.digitalocean.com/community/tutorials/how-to-add-swap-on-ubuntu-14-04 for an awesome breakdown!

Posted in Linux Tagged with: ,

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>