Change SWAP memory in Linux/Debian
Introductionβ
To safely increase your swap size on Ubuntu without affecting your existing files, follow the method of creating a new swap file (instead of touching existing partitions). This is safe, easy, and reversible.
Letβs say you want to increase swap from 2 GB to 4 GB.
1οΈβ£ Step 1: Check current swapβ
sudo swapon --show
free -h
π¦ Step 2: Turn off current swap (temporarily)β
sudo swapoff -a
π§Ή Step 3: Remove old swap file (only if you're replacing /swapfile
)β
Skip this if you plan to keep the old one.
sudo rm /swapfile
π§± Step 4: Create a new swap file (e.g., 4 GB)β
Here instead of 4G
you can change the size, For e.g.: 6G
, 8G
, 16G
and so on.
sudo fallocate -l 4G /swapfile
# If fallocate fails (e.g., on some file systems), use:
# sudo dd if=/dev/zero of=/swapfile bs=1M count=4096
π Step 5: Set proper permissionsβ
sudo chmod 600 /swapfile
π Step 6: Make it swapβ
sudo mkswap /swapfile
β Step 7: Enable swapβ
sudo swapon /swapfile
Verify:
sudo swapon --show
free -h
πΎ Step 8: Make it permanent (survives reboots)β
Edit /etc/fstab
:
sudo nano /etc/fstab
Make sure you have this line:
/swapfile none swap sw 0 0
β All Done! Your server now has a bigger swap space.
π Safety Tips
- This method doesn't touch existing partitions β so your data is safe.
- Donβt use a swap file on SSDs heavily unless absolutely needed (wear).
- Donβt make swap too large (e.g., > 8 GB) unless running memory-heavy apps.
Congratulations! πβ
You have successfully change the size of swap memory in your system. β
