swap

If you see that your server is running out of swap you should add more RAM, nevertheless this is not always possible or maybe you need that extra amount for a very specific usage.

If this is the case you just need to add some more swap to your system. There are several usage cases I’ll just cover the 2 most common ones, with and without LVM.

 

Adding swap space without LVM

If you’re not using LVM and you don’t have any other location to put your new swap partition you can do it in one of the file systems available in the system.

  • Create a file that can be use as swap, if you have more than one file system available choose the one with best performance, in this case we will use /, the file will have 16GB and it will be called extra_swap.fs.

dd if=/dev/zero of=/extra_swap.fs count=16000 bs=1048576

  • Format the file

mkswap /extra_swap.fs

  • Set the right permissions the file

chmod 600 /extra_swap.fs; chown root:root /extra_swap.fs

  • Enable it

swapon /extra_swap.fs

  • Make it permanent (if needed)

echo “/extra_swap swap swap defaults 0 0 ” >> /etc/fstab

 

Adding swap space with LVM (method 1)

This method applies if you have LVM and you’re not able to disable swap (for instance production servers that have a high system load and memory usage)

  • Add a new volume with 16G (on volume called VolumeGroupName, you will need to adjust this to the desired volume group)

lvcreate -n extra_swap_lv -L16G VolumeGroupName

  • Format the volume

mkswap /dev/VolumeGroupName/extra_swap_lv

  • Enable it

swapon  /dev/VolumeGroupName/extra_swap_lv

  • Make it permanent (if needed)

echo ” /dev/VolumeGroupName/extra_swap_lv swap swap defaults 0 0 ” >> /etc/fstab

 

Adding swap space with LVM (method2)

If you are able to disable swap for a while (<10minutes) this is the recommended method.

  • Disable  your current swap volume (please take in consideration that this can have a negative impact on performance, use with caution).

swapoff swap_volume_name

  • Expand your current volume, by adding 16GB to the volume swap_volume_name ( you will need to adjust this to the desired logical volume)

lvextend -L+16G swap_volume_name

  • Format the volume

mkswap /dev/VolumeGroupName/swap_volume_name

  • Enable it

swapon  /dev/VolumeGroupName/swap_volume_name

 

References

Check the excellent REHL manual about swap.

 

I hope you don’t have to go through this, as said before the best is to buy some new ram.

Cheers,

Pedro M. S. Oliveira