What is Swap Space?
Swap space is a designated area on your hard drive that the Linux kernel uses as virtual memory. When your system runs out of physical RAM, inactive pages in memory are moved to the swap space, freeing up RAM for active processes. While swap on a hard drive is significantly slower than RAM, it is a crucial safety net that prevents Out of Memory (OOM) crashes on busy Ubuntu servers.
Step 1: Check Current Swap Usage
Before creating new swap space, check if your system already has swap configured. Open your terminal and run:
sudo swapon --show
If the output is empty, your system does not have swap enabled. You can also verify this by checking the free -h command; the Swap row will show 0B.
Step 2: Create a Swap File
The easiest way to add swap is by creating a swap file (as opposed to partitioning a disk). To create a 4 Gigabyte swap file at the root of your filesystem, use the fallocate command:
sudo fallocate -l 4G /swapfile
If fallocate is not available, you can use the dd command as an alternative:
sudo dd if=/dev/zero of=/swapfile bs=1G count=4
Step 3: Secure and Format the Swap File
For security reasons, only the root user should be able to read and write to the swap file, as it may contain sensitive data swapped out of memory. Secure the file by adjusting its permissions:
sudo chmod 600 /swapfile
Next, format the file as swap space using the mkswap utility:
sudo mkswap /swapfile
Step 4: Enable the Swap Space
With the file formatted, tell the system to begin utilizing it as swap memory:
sudo swapon /swapfile
Run sudo swapon --show again, and you should now see your /swapfile listed with a size of 4G. You can also run free -h to confirm the system recognizes the new virtual memory.
Step 5: Make the Swap File Permanent
Currently, the swap file is enabled, but it will be lost if the server reboots. To make the change persistent, you must add it to the /etc/fstab file.
First, back up the fstab file in case of mistakes:
sudo cp /etc/fstab /etc/fstab.bak
Next, append the swap file configuration to the end of the fstab file by running:
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Your Ubuntu server is now permanently configured with additional swap space, significantly increasing its stability under heavy memory loads.