This article shows you how to easily add swap to CentOS using a file on it’s existing storage systems.
What is a swap file (swap patition)?
When your CentOS server runs out of physical memory (or RAM) Linux has the ability to swap blocks (aka pages) of memory out to a swap area. It’s smart and tries to swap out the least used chunks of memory first. If you don’t have swap space, and your server uses up all it’s memory you’re going to start having processes die horribly with out of memory (OOM) errors. So swap provides an automagic buffer to stop you running out of physical memory. Here’s the Wikipedia article on paging if you want more info about the general concept.
The problem is that, compared to RAM, swap space is very slow. So if you’re relying on it all the time, you’re system speed is really going to suffer. That said, there’s times when a brief spike of memory usage can really benefit from having some swap space kicking around.
How to add Swap on CentOS
Step 1 – Check your existing swap setup
To check your existing swap setup you can run:
Step 2 – Make a file to use as swap space
In this example we’re going to make a 512MB file called /swap which will serve as a our swap space.
Step 3 – Set your newly created file up as swap space
[[email protected] ~]# mkswap /swap
mkswap: /swap: warning: don't erase bootbits sectors
on whole disk. Use -f to force.
Setting up swapspace version 1, size = 524284 KiB
no label, UUID=95aa78a4-06a9-42af-9155-2dc3cd87dffa
[[email protected] ~]#
Step 4 – Add your space to the system
That should be it all done and available for use.
Step 5 – Check it’s working
Use either of these command to make sure your system now sees the swap space:
[[email protected] ~]# swapon -s
Filename Type Size Used Priority
/swap file 524280 0 -1
[[email protected] ~]# free -m
total used free shared buffers cached
Mem: 992 613 378 0 3 545
-/+ buffers/cache: 65 927
Swap: 511 0 511
Step 6 – Set the swap space to activate on boot
To make the swap space automatically mount at boot time we need to at it to the
Edit the file (nano -w /etc/fstab) and paste in:
swap /swap swap defaults 0 0
To check that’s worked reboot and then type:
And that’s everything you should need to know to add swap space to your CentOS system. Feel free to leave feedback in the comments section below.
Thanks for stopping by.