How to add and increase swap on CentOS

Adding a swap file without reboot

If you are having a dedicated server somewhere with not that much memory, you could decide to add a swap without rebooting your server.

To do so, you need to follow the routine:

sudo dd if=/dev/zero of=/swapfile count=1024 bs=1MiB
sudo mkswap /swapfile
sudo chmod 0600 /swapfile
sudo swapon /swapfile

Increasing a swap size

If something goes wrong with your system, and you see that your swap file is full

$ sudo swapon --show
#NAME       TYPE  SIZE    USED PRIO
# /swapfile  file 1024M 1023.8M   -2

Then you would want to increase it. But most of the time you cannot just remove a swap file and add a bigger one.
What you can do is adding a new temporary file without removing an existing one, the remove the original one, add it again with increased size, and finally remove the temporary file. Like this:

# add a temporary file
$ sudo dd if=/dev/zero of=/swapfile_tmp count=1024 bs=1MiB
$ sudo mkswap /swapfile_tmp
$ sudo chmod 0600 /swapfile_tmp
$ sudo swapon /swapfile_tmp
# then you will see something like below
$ sudo swapon --show
# NAME       TYPE  SIZE    USED PRIO
# /swapfile  file 1024M 1023.8M   -2
# /swapfile_tmp file 1024M    3.3M   -3

# now remove the original file
$ sudo swapoff /swapfile

# add it back with increased size - 4Gb instead of 1Gb in my case
sudo dd if=/dev/zero of=/swapfile count=4096 bs=1MiB
sudo mkswap /swapfile
sudo chmod 0600 /swapfile
sudo swapon /swapfile

# now remove the temporary file
$ sudo swapoff /swapfile_tmp

# here is the result
$ sudo swapon --show
# NAME      TYPE SIZE USED PRIO
# /swapfile file   4G 1.1G   -2

LEAVE A COMMENT