If your Ubuntu system is running low on memory, adding swap space can help improve performance and prevent crashes due to insufficient RAM. In this guide, we’ll walk you through setting up swap space on your Ubuntu server step by step.

What is Swap Space?

Swap space is a portion of your disk storage that acts as virtual memory. When your system runs out of RAM, it temporarily moves inactive processes to the swap space, freeing up RAM for active processes. While swap is slower than RAM, it can be a lifesaver for systems with limited memory.

Checking If Swap is Enabled

Before setting up swap, check whether your system already has swap space enabled by running:

free -m

If you see Swap: 0 0 0, it means there is no swap space configured.

Creating a Swap File

Follow these steps to create and enable a swap file:

Step 1: Allocate Space for Swap

You can create a 1GB swap file using the fallocate command:

sudo fallocate -l 1G /swapfile

If fallocate is not available, use dd instead:

sudo dd if=/dev/zero of=/swapfile bs=1M count=1024

Step 2: Set Proper Permissions

Change the file permissions to restrict access:

sudo chmod 600 /swapfile

Step 3: Format the Swap File

Next, format the file as swap space:

sudo mkswap /swapfile

Step 4: Enable Swap

Activate the swap file with:

sudo swapon /swapfile

To verify that swap is active, run:

free -m

Now you should see swap space listed.

Step 5: Make Swap Permanent

To ensure swap remains enabled after a reboot, add it to /etc/fstab:

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

Adjusting Swap Settings

You can adjust swap settings to optimize performance:

Modify Swappiness

Swappiness determines how often the system uses swap. A value of 0 minimizes swap usage, while 100 aggressively swaps. To check the current swappiness:

cat /proc/sys/vm/swappiness

To temporarily change it to 10 (recommended for servers):

sudo sysctl vm.swappiness=10

To make it permanent, add the following line to /etc/sysctl.conf:

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

Modify Cache Pressure

To reduce the tendency to clear file system caches, adjust vm.vfs_cache_pressure:

echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf

Conclusion

Setting up swap in Ubuntu is a straightforward process that can significantly improve system stability, especially on low-memory machines. By following these steps, you can ensure that your system has the necessary virtual memory to handle heavy workloads efficiently.