How to add SWAP space on CentOS

The easiest way to prevent out of memory errors in your system is to add some SWAP space. SWAP is an area on the storage device where the system can temporarily store data that can’t be held in memory (RAM). Though this is working as the memory it is slower in performance than regular memory. However, when the system is out of memory it may kill processes to keep applications running or, the whole system can crush too. It is possible to keep the applications running without killing processes and stop system crushing by adding enough SWAP space.

Prerequisites

  • CentOS 6.xx
  • CentOS 7.xx
  • sudo / root user

Step 1 – Create SWAP File

Use below command to create a 4GB SWAP File

dd if=/dev/zero of=/swapfile count=4096 bs=1MiB

change count value to change SWAP file size.

Step 2 – Enable SWAP File

Change the SWAP file permission

chmod 600 /swapfile

Make the SWAP file ready

mkswap /swapfile

Enabling SWAP space for system

swapon /swapfile

Step 3 – Verify SWAP Space

Verify total SWAP space using this command

swapon -s
Filename        Type           Size           Used     Priority
/swapfile          file         4194300         0             -1

Such output confirms that you successfully added 4GB SWAP on the system.

Step 4 – Make SWAP Space Permanent

Though we already have added 4GB SWAP space in the system but when the system reboots it will not use this SWAP space automatically. We can change this by modifying fstab file which manages the file systems and partitions.

nano /etc/fstab

Place these in the bottom of the fstab file and save the file

/swapfile    swap    swap    sw  0   0

Please check if there are any lines for SWAP space already, if there is remove it first.
Once you have saved the file system will automatically use the SWAP space upon system reboots.

Don’t hesitate to comment regarding any issue you might face during the procedure.

Thanks for reading this article.

Add comment

By Tonmoy Ajize

About Author

Tonmoy Ajize

Hey There! I am Tonmoy Ajize from Dhaka, Bangladesh. I am a Linux System Administrator and Customer Success Specialist.