Skip to content

Instantly share code, notes, and snippets.

@jeanpauldejong
Last active June 27, 2025 08:27
Show Gist options
  • Save jeanpauldejong/335e7dc88cdc1df662f390e9ee64cf11 to your computer and use it in GitHub Desktop.
Save jeanpauldejong/335e7dc88cdc1df662f390e9ee64cf11 to your computer and use it in GitHub Desktop.
Enable Swap on Ubuntu

Enable Swap on Ubuntu

Create a swap file on Ubuntu to increase system performance by allowing the system to use disk space as virtual memory.

Create a 2GB swap file:

sudo fallocate -l 2G /swapfile

If fallocate is not available, you can use dd:

sudo dd if=/dev/zero of=/swapfile bs=1G count=2

Set the correct permissions for the swap file:

sudo chmod 600 /swapfile

Make the file a swap file:

sudo mkswap /swapfile

Enable the swap file:

sudo swapon /swapfile

To make the swap file permanent, add it to /etc/fstab:

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

To verify that the swap file is active, you can use:

swapon --show

To check the total swap space available, you can use:

free -h

Swap File Tuning (Optional)

To adjust the swappiness value (optional), which controls how often the system uses swap space, you can edit /etc/sysctl.conf:

sudo nano /etc/sysctl.conf

Add or modify the following line:

vm.swappiness=10

Then apply the changes:

sudo sysctl -p

Note: The default value is usually 60, and setting it to a lower value (like 10) reduces the tendency to use swap space.

Swap File Management

To disable the swap file, you can use:

sudo swapoff /swapfile

To remove the swap file, you can use:

sudo rm /swapfile

Additional Notes:

  • This guide provides a simple way to enable and manage swap files on Ubuntu systems.
  • Adjust the size of the swap file and swappiness value according to your system's needs.
  • Always ensure you have sufficient disk space before creating a swap file.
  • This can help improve system performance, especially on systems with limited RAM.
  • Remember to monitor your system's performance and adjust the swap settings as necessary.
  • For more advanced configurations, consider using a swap partition instead of a swap file.
  • This guide is applicable to most Ubuntu versions, including Ubuntu Server and Desktop editions.
  • Always back up important data before making changes to system configurations.
  • For more information, refer to the official Ubuntu documentation on swap files.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment