How To Add Swap Memory On Ubuntu 18.04
Hello everyone, we all facing sometimes out-of-memory errors in system because of we don’t have enough ram in system. In this case we added swap memory to the system to resolved this issue.
What Is Swap Memory ?
Swap memory is the second type of memory in modern Linux systems. Swap memory is the area on a hard disk that has been designated as a place where the operating system can temporarily store data that it can no longer hold in RAM.
Step 1 :- Checking The System
Before we begin, we can check the system RAM and swap memory using following command
If you get swap row of the output is “0B”. Then there is no swap is active on the system.
Step 2 :- Checking The Hard Disk Space
Before we create our swap file, we first check our current disk usage to make sure we have enough space to create swap file. We can check the disk usage using following command
Step 3 :- Creating A Swap File
Now we are going to create the swap file under root directory(/) and give name as ‘swapmemory’ .
The best way to create a swap file with the “fallocate” command. This command instantly creates a file of the specified size.
The best practices is whenever you create swap the swap size is must be twice of your system ram.
sudo fallocate -l 4G /swapmemory sudo chmod 600 /swapmemory
For creating file in the root directory(/) you required the sudo privileges. In above command I am going create the “swapmemory” file of 4GB.
After that I am going the change permission of that file to 600 . 600 is only read and write for owner of the file and for other users there is no permission.
Step 4 :- Enabling The Swap Memory
In this step, we are setup the swap area using mkswap command. mkswap is just like other mkfs-like utils. Erases the first partition block to make any previous file system invisible.
sudo mkswap /swapmemory
After marking the file, we can enable the swap memory, using following command
sudo swapon /swapmemory
Step 5 :- Verify The Swap Is Available
We can verify swap using following commands
sudo swapon --show free -h
Step 6 :- For Permanent Enable of Swap Memory
Our swap has been set up successfully. But there is one issue on next reboot our swap memory is not accessible.
For enable permanent swap memory we are going to add the entry in /etc/fstab file.
sudo cp /etc/fstab /etc/fstab.bak vi /etc/fstab
first we take the backup /etc/fstab file. After that we open that file(don’t remove anything from that file) on new line just add following things
/swapfile none swap sw 0 0
You can save that file using “Esc + :wq”
Step 7 :- Verify The Swap Is Permanent Available Or Not
Now we are going to reboot our system. After that execute following command to check weather our swap is mount or not.