Linux

How to add Swap Space on linux

Adding swap space on a Linux system is a useful way to increase the amount of virtual memory available. This can be particularly helpful when your system runs out of physical RAM. Here's a step-by-step guide on how to add swap space on a Linux system:

Step 1: Check Existing Swap Space
First, check if your system already has swap space enabled:

sudo swapon --show
free -h

If you see output from `swapon --show`, you already have swap enabled. The `free -h` command will show you how much swap is in use and how much is available.

Step 2: Create a Swap File
Decide the amount of swap space you want to add. As a rule of thumb, the size of the swap should be equal to or double the amount of RAM, although this depends on your specific needs and system usage.

To create a swap file of, say, 4 GB, you can use:

sudo fallocate -l 4G /swapfile

Alternatively, if `fallocate` doesn't work, you can use `dd`:

sudo dd if=/dev/zero of=/swapfile bs=1G count=4

Step 3: Set the Swap File Permissions
Only the root should have read and write permissions for the swap file:

sudo chmod 600 /swapfile

Step 4: Format the File for Swap
Next, turn the file into a swap space:

sudo mkswap /swapfile

Step 5: Enable the Swap File
Now, enable the swap file so that the system starts using it:

sudo swapon /swapfile

Step 6: Verify the Swap Space
Check if the swap is active:

sudo swapon --show
free -h

Step 7: Make the Swap File Permanent
To ensure the swap file is enabled on boot, edit the /etc/fstab file:

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

Step 8: Adjust Swappiness Value (Optional)
The `swappiness` parameter configures how often your system uses swap space. It's a value between 0 and 100; the default is usually set to 60. Lower values are typically better for desktop systems to ensure a fast response time.

Check the current swappiness value:

cat /proc/sys/vm/swappiness

To change the swappiness to a lower value, like 10:

sudo sysctl vm.swappiness=10

To make this change permanent, add it to `/etc/sysctl.conf`:

echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf

This procedure covers the essential steps to add swap space on a typical Linux system. Adjust the sizes and parameters according to your specific needs and system configurations.