Swap is a space on a disk that is used when the amount of physical RAM memory is full. When a Linux system runs out of RAM, inactive pages are moved from the RAM to the swap space. However, in this tutorial we will cover how to create a Swap File on Ubuntu server
Creating the Swap File
01- To create a swap file we can use fallocate
or dd
, for this tutorial we will create a file called swapfile in the root (/) directory with 100 MB of size.
# sudo fallocate -l 100M /swapfile
or you can use dd
command
# sudo dd if=/dev/zero of=/swapfile bs=1024 count=102400
02- Adjusting the permissions on the swap file:
# sudo chmod 600 /swapfile
03- Setting up the swap file:
# sudo mkswap /swapfile
04- Enable the swap file immediately:
# sudo swapon /swapfile
05- Check the total system swap space:
# sudo swapon -s
Enable the swap file automatically at boot time
The Swap File is enabled at the moment, but when we reboot, the Swap File will be not automatically enabled for the use, for that reason we will add some entry to the /etc/fstab file to enable it automatically at boot time
01- Open the /etc/fstab
file and add this line in the end:
/swapfile swap swap defaults 0 0
02- you can verify it is enabled by viewing the output of the command cat /proc/swaps or free
# cat /proc/swaps # free -h
Removing a Swap File
To deactivate and delete the swap file, follow these steps:
01- First, deactivate the swap space:
# sudo swapoff -v /swapfile
02- Next, remove the swap file entry /swapfile swap swap defaults 0 0
from the /etc/fstab
file.
03- Finally, remove the actual swapfile
file using the rm
command:
# sudo rm /swapfile
Conclusion
You have learned how to create a swap file and activate and configure swap space on your Ubuntu system.
You might want to check the following guides: