Create a Swap file on CentOS 7

Tech
6 Comments

Even if you have sufficient memory in your server, it’s still a good idea to have a swap file.  In order to reduce disk IO, many cloud providers don’t include one as standard – so you may need to add your own.

If you need a server to try this out on, we recommend our friends at Linode.

Firstly, you can use the following command to check if you have any swap space already:

free -m

The following output shows zero swap space

              total        used        free      shared  buff/cache   available
Mem:           7822        1390         506         492        5924        5569
Swap:             0           0          0

Now we need to create the swap file – I’m going to create a 4GB file, but you can adjust the values to your needs:

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

Now set the permissions:

sudo chmod 600 /swap

and format the swap file:

sudo mkswap /swap

To enable the swap file just use:

sudo swapon /swap

To make the swap be automatically mounted after reboot, the following command will add it to your fstab config:

sudo echo "/swap swap swap sw 0 0" >> /etc/fstab

We can now test our swap file to make sure all is well.  Firstly, running ‘free -m’ again should yield a different result:

              total        used        free      shared  buff/cache   available
Mem:           7822        1390         506         492        5924        5569
Swap:          4095           0        4095

And we can check the swap file by using ‘sudo swapon -s’

Filename  Type  Size     Used  Priority
/swap     file  4194300  0     -1

You’re now all setup with your swap file.

6 Comments. Leave new

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu