Add swap memory space on Linux servers

The steps may be somewhat similar to every distribution with a minor difference of file locations or otherwise. Usually, when I face issues with less memory or Swap increase i have used this method several times successfully to add Swap memory space in Linux servers CentOS, Ubuntu or Debian.

Disclaimer: These commands otherwise won’t make much harm and I have done my research to get these steps from the internet and various communities. However, I myself or this website are not responsible for any outcome what so ever. If you are not sure please do your research before finalizing these commands on Live server. Using the commands on the test server first or dummy server is highly recommended.
Remove swap entry

Lets try to add swap memory space in Linux server.

If you already have an existing SWAP memory space in Linux Servers first we can disable it using the next command. (I am comfortable with nano file editor however its your choice if you using vi or nano.)

# nano /etc/fstab

Next, we Comment out swap entry in this file if you already have an entry. If you don’t have any entry or Swap memory added you can just ignore this step.

Next We turn SWAP off by using command

# Swapoff -a
We can verify the Swap status is turned off by command.
# Swapon -s
This command will not return you any details hence we may assume that the Swap is turned off now.

Lets Add Swap Memory Space to your Linux Server

# sudo dd if=/dev/zero of=/swapfile count=4096 bs=1MiB
# sudo chmod 600 /swapfile
# sudo mkswap /swapfile
# sudo swapon /swapfile

Now we have added a swap file and allotted the required permissions recommended. Hence, now we will have to enable the swap entry in the required file.

# sudo nano /etc/fstab
If you commented out this from step 1 then just remove the comment or if you did not have any Swap Space Entry earlier you can Add following on last line, save and exit.

/swapfile swap swap defaults 0 0

Next we define SWAPINESS – this is the second part of adding the Swap Memory Space to Linux Server

# sudo sysctl vm.swappiness=10

We will declare the spwainess in the system ctl file so that each time server reboots we are sure to have our configuration for swapiness workng.

# sudo nano /etc/sysctl.conf
Now add the following to the last line, save and exit.

vm.swappiness = 10
vm.vfs_cache_pressure = 50

Lastly, we need to just make sure everything is good to go. So usually, I make a # reboot to be assured that after reboot the swap space is good and added to the configuration.
#reboot

Once the server is rebooted now you can simply check the Swap space by typing:
#swapon -s
# free -m

Leave a Comment

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

× Connect Now!