How to change the size of your swap file?

One of the most frequently asked questions, while working in support, is 'how to change the size of the swap file'. I'll tackle this topic by providing a short introduction to the matter, with a couple of use case and with the step by step guide. Let's get started!

What is it?

Swap (Virtual Memory) is space on a disk that Linux can use it when it runs out of RAM. Inactive processes can be moved to swap from RAM to make space for active processes.

However there is a disadvantage since hard disk is much slower than RAM, your server performance can slow down.

Cloud 66 create a swap file on provisioning servers in root folder /c66-swapfile. The size of the file depends on free space of the server that is between 3 GB to 256 GB.

Reasons to change the size of the swap file

You may need to change swap in different cases, for example:

  • When your box ran out of spaces, decreasing swap file size is the quickest way that you can release some spaces, especially when you have a huge swap file.

  • When you have a server with lots of processes running on it, increasing swap file will let the kernel to move inactive processes into swap to make room for active processes in the working memory.

Step-by-step guide

The instruction below will help you change your server swap file size to desired value.

First, you need to create a script that you can re-use it.

  • Create a file named /tmp/swap-file-setter.sh with script below
#!/bin/bash
# don't do anything if we already have swap file settings
if [[ $(swapon -s | wc -l) = 1 ]] ; then  
  echo "Creating your swap file"
  dd if=/dev/zero of=/c66-swapfile bs=1024 count=$1k
  mkswap /c66-swapfile
  swapon /c66-swapfile
  echo "/c66-swapfile      none    swap    sw      0      0 " >> /etc/fstab
  chown root:root /c66-swapfile
  chmod 0600 /c66-swapfile
  echo "Swap file successfully created"
fi  
  • Give executing permission to the script
sudo chmod +x /tmp/swap-file-setter.sh  

Now you can use the script each time you wish to change the swap file size.

  • Remove the current swap file
$ sudo swapoff -a
$ sudo rm -f /c66-swapfile
  • Create a new swap file using script above
sudo /tmp/swap-file-setter.sh <size_in_mb>  

To sum up, managing swap space is an essential aspect of system administration. Always monitor your memory to ensure that you are getting the best result with your current swap file size.

More read:

Try Cloud 66 for Free, No credit card required