Rabu, 05 Februari 2025

How to Add Swap in Linux

Adding Swap in Linux

How to Add Swap in Linux

1. Check if swap is already enabled

free -h
swapon --show

2. Create a swap file

sudo fallocate -l 2G /swapfile

# If fallocate is not available, use:
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048

3. Set file permissions

sudo chmod 600 /swapfile

4. Format the file as swap

sudo mkswap /swapfile

5. Enable the swap file

sudo swapon /swapfile

6. Add to /etc/fstab for persistence

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

7. Verify that swap is active

free -h
swapon --show

8. (Optional) Optimize Swappiness

Reduce swappiness value to use swap only when RAM is nearly full:

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

9. (Optional) Remove Swap if No Longer Needed

sudo swapoff -v /swapfile
sudo rm /swapfile
sudo sed -i '/\/swapfile/d' /etc/fstab

These are the steps to add swap in Linux. Hope this helps!

Share: