Thursday, February 2, 2023

Creating a SWAP partition in Debian/Ubuntu Linux


Add some swap space to your server as a defence against out-of-memory issues in apps. We shall discuss adding a swap file to a Debian/Ubuntu server in this blogpost.

What is Swap?

Swap is a portion of hard drive storage that has been set aside for the operating system to temporarily store data that it can no longer hold in RAM. This lets you increase the amount of information that your server can keep in its working memory, with some caveats. The swap space on the hard drive will be used mainly when there is no longer sufficient space in RAM to hold in-use application data.

Creating a swap partition

STEP 1: First step is to check if by chance is there any SWAP partition already created in your PC:

sudo swapon --show

Enter your root password. If you see no output, it means that the SWAP doesn’t exist.

STEP 2: Next, let’s see the current partition structure of your computer’s hard disk:

df -h

STEP 3: Before you start the changes disable the use of swap:

sudo swapoff -a

STEP 4: Now it's time to create the SWAP file. Make sure you have enough space on the hard disk. It is a matter of preference in how much SWAP size you need.

My suggestion is: If you have a maximum of 4GB of RAM I would suggest putting twice the RAM for the SWAP (8GB for SWAP). For PCs with more than 4GB I recommend the same number of RAM for SWAP plus 2GB. Example: In my case it's 4GB, I put 8GB for SWAP. But you may feel free to make your choice.

sudo fallocate -l 8G /swapfile

We can verify that the correct amount of space was reserved by typing:

ls -lh /swapfile

STEP 5: SWAP file is now created. Let’s give root-only permissions to it.

sudo chmod 600 /swapfile

STEP 6: Mark the file as SWAP space:

sudo mkswap /swapfile

STEP 7: Finally enable the SWAP.

sudo swapon /swapfile

STEP 8: You can now check using the same swapon command to check if SWAP is created.

sudo swapon --show

STEP 9: Also check the final partition structure again.

free -h

STEP 10: Once everything is set, you must set the SWAP file as permanent, else you will lose the SWAP after reboot. Run this command:

Back up the /etc/fstab file in case anything goes wrong:

sudo cp /etc/fstab /etc/fstab.bak

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Adjusting the swappiness and Cache Pressure

Change current swappiness value and Cache Pressure 10, 50 respectively by typing:

sudo sysctl vm.swappiness=10

sudo sysctl vm.vfs_cache_pressure=50

This setting will persist until the next reboot. We can set this value automatically at restart by adding the line to our /etc/sysctl.conf file:

sudo nano /etc/sysctl.conf



Finished, now exit the terminal!


No comments:

Post a Comment