You are currently viewing How to Create a Swap file on CentOS 7

How to Create a Swap file on CentOS 7

  • Post author:
  • Post category:Linux

In this blog article, I will teach you how to create a swap file on CentOS 7 speficially, but this command should work fine on any other Linux distributions.

It’s always a good idea to have a swap file.

 

 

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.

 

Reference

Reference