Running out of memory on your Ubuntu system? If your applications are sluggish or crashing under heavy load, it might be time to increase your swap space. Swap is the portion of disk used as virtual memory when RAM is full. It’s not a performance booster, but it can prevent crashes and keep things running when RAM is maxed out.
Here’s a no-nonsense guide to increasing swap size on Ubuntu.
Check Your Current Swap Setup
First, see how much swap you’re using:
swapon --show
If that returns nothing, you probably don’t have swap configured. You can confirm with:
free -h
Step 1: Turn Off Existing Swap (If Needed)
If you’re increasing an existing swap file:
sudo swapoff /swapfile
Step 2: Resize or Create a New Swap File
Option A: Resize Existing Swap File
Let’s say you want to increase it to 4GB:
sudo dd if=/dev/zero of=/swapfile bs=1G count=4
Or if you already have a swap file and just want to resize it:
sudo truncate -s 4G /swapfile
Option B: Create a New Swap File (if none exists)
sudo fallocate -l 4G /swapfile
Step 3: Set Correct Permissions
sudo chmod 600 /swapfile
Step 4: Format the Swap File
sudo mkswap /swapfile
Step 5: Enable the Swap File
sudo swapon /swapfile
To confirm:
swapon --show
Step 6: Make It Permanent
Edit the /etc/fstab
file:
sudo nano /etc/fstab
Add this line if it’s not already there:
/swapfile none swap sw 0 0
Save and exit.
Bonus: Adjust Swappiness (Optional)
Swappiness controls how aggressively Ubuntu uses swap. Default is 60. If you want it to favor RAM more, lower it:
sudo sysctl vm.swappiness=10
To make it permanent:
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
Done
That’s it. You’ve increased your swap space. This can be a lifesaver for servers, older machines, or systems doing heavy multitasking.
Have questions or want help tweaking your system? Drop them in the comments below.
Leave a Reply