How to create the swap space using the swap file on Ubuntu 20.04?
Introduction:
Swap space is a dedicated area on a computer’s hard drive that is used as virtual memory when the system’s physical RAM (Random Access Memory) is full. When the RAM becomes overloaded, the operating system moves less frequently used data from RAM to the swap space, freeing up memory for more immediate tasks. Ubuntu 20.04.
Prerequisite
1. Server root login credentials.
Step 1:
Log in to your Ubuntu 20.04 server as a user with sudo privileges. You can use SSH or directly access the server.
$ ssh root@Ip |
Step 2:
Check the available disk space using the df
command to ensure you have enough space to create the swap file. Swap files are typically recommended to be around 2-4 times the size of your RAM.
Step 3:
Determine the location where you want to create the swap file. For this example, let’s create it in the root directory (/
).
Step 4:
Open a terminal or SSH session and run the following command to create a swap file with the desired size (replace <swapfile_size>
with the desired size in megabytes):
$ sudo dd if=/dev/zero of=/swapfile bs=1M count=<swapfile_size> |
Step 5:
Set the appropriate permissions on the swap file:
$ sudo chmod 600 /swapfile |
Step 6:
Set up the swap space on the file by running the following command:
$ sudo mkswap /swapfile |
Step 7:
Activate the swap space by running the following command:
$ sudo swapon /swapfile |
Step 8:
Verify that the swap space is active and available by using the free
command
$ free -m |
Step 9:
To make the swap file persist across reboots, open the /etc/fstab
file with root privileges:
$ sudo nano /etc/fstab |
Step 10:
Add the following line at the end of the file:
/swapfile none swap sw 0 0
Step 11:
Save and close the file
Conclusion:
Swap space plays a crucial role in managing system memory effectively. By creating a swap space using a swap file on Ubuntu 20.04, you can improve the performance and stability of your system, especially when dealing with memory-intensive tasks.
In this blog we have seen how to create swap space from system RAM space.