How to increase the size of the swap in Ubuntu
To increase the swap size in Ubuntu, you begin by disabling the current swap with sudo swapoff -a, optionally, removing the existing swap file if you plan to replace it. Then, a new swap file is created, typically fallocate for speed (sudo fallocate -l 40G /swapfile) or dd for broader compatibility. Once the file is created, it must be secured with the correct permissions (chmod 600) to ensure only the root can access it. Next, the file is formatted as swap using mkswap and enabled with swapon.
To make the change persistent after reboot, you need to edit the /etc/fstab file and add the line /swapfile none swap sw 0 0. This ensures the swap file is automatically activated on boot. You can verify that the new swap size is active using commands like swapon --show or free -h. This approach is effective for improving system performance, especially on low-memory machines or when running memory-intensive applications, without needing to repartition your disk.
Resize the existing swap file
1. Turn off swap
sudo swapoff -a2. Remove Old Swap File (if you want to replace it
sudo rm /swapfile3. Create a New 40 GB Swap File
sudo fallocate -l 40G /swapfile
sudo dd if=/dev/zero of=/swapfile bs=1G count=404. Secure the File
sudo
chmod 600 /swapfile5. Format as Swap
sudo mkswap /swapfile6. Enable the Swap
sudo swapon /swapfile7. Make It Permanent
sudo nano /etc/fstab/swapfile none swap sw 0 08. Verify Swap Size
swapon --showfree -h