Creating a Swap File

Most cloud computers don’t come with swapping pre-enabled. There can however be times where this is required and/or beneficial. The process is pretty much the same for any Linux distro.

To the the current state of your swap, use the below command.

[root@centos7 ~]# free -m

Create the swap file with the dd command. Below we create an 8GB (8 x 1024 = 8192) block device file and fill it with zeros.

[root@centos7 ~]# dd if=/dev/zero of=/swap bs=1024 count=8192

Restrict permissions to root.

[root@centos7 ~]# chmod -v 600 /swap
mode of ‘/swap’ changed from 0644 (rw-r--r--) to 0600 (rw-------)

Create the swap space.

[root@centos7 ~]# mkswap /swap
Setting up swapspace version 1, size = 8188 KiB
no label, UUID=07720bbf-e1d0-42f9-a358-5b4ba1667c6b

Tell our system to use the swap space.

[root@centos7 ~]# swapon -v /swap

Confirm that works with swapon -s. This of course is not permanent until you create an entry for it in /etc/fstab.

[root@centos7 ~]# swapon -s
Filename				Type		Size	Used	Priority
/swap                                  	file	8188	0	-1

To make it permanent, edit /etc/fstab:

[root@centos7 ~]# vim /etc/fstab

And enter the below.

/swap       none           swap          sw               0 0

Done! Should you decide you now want to remove the swap file:

swapoff -v /swap
rm -v /swap

Don’t forget to also remove the entry from fstab.

Be the first to comment

Leave a Reply