I describe how to add swap to CentOS and why using dd instead of fallocate for this.


In my case, I wanted to take the opportunity of an AWS promotion, which limits the DRAM to 1 GB. The CentOS Docker Host I am using for Angular CLI topics needs slightly more than 1 GB or RAM. Instead of upgrading the AWS plan, I have decided to try it with adding a swap file.


First, I have followed this Ubuntu instructions, because I wanted to test the fallocate function on CentOS. This looked less hardware-related than the dd commands I have found on the CentOS instructions.

Fallocate seemed to work at first sight, but when it came to the activation as swap, I got an error message also discussed on this StackExchange page.:

$ sudo swapon /myswap
swapon: /myswap: swapon failed: Invalid argument

I had to revert back to the CentOS instructions:

Step 1: Create File with dd

Multiply the number of MB by 1024 (in my case: 2 GB = 2014 MB; multiplied with 1024, this is 2097152):

$ sudo dd if=/dev/zero of=/swapfile bs=1024 count=2097152

This takes some time; it is zeroing out 2 GB of disk space…

Step 2: Correct Permissions

We correct the permissions of the swapfile:

$ sudo chmod 600 /swapfile
$ ls -lh /swapfile
-rw-------. 1 root root 2.0G Oct  1 09:48 /swapfile

Step 3: Declare as Swap

We mark the file as swap:

$ sudo mkswap /swapfile
Setting up swapspace version 1, size = 2097148 KiB
no label, UUID=e57fba27-064a-456b-be56-32fb230eede0

Step 4: Activate Swap

Now the swapfile can be activated:

$ sudo swapon /swapfile

Step 5: Verify

To verify:

$ free -h
              total        used        free      shared  buff/cache   available
Mem:           991M         71M         70M         12M        849M        738M
Swap:          2.0G          0B        2.0G

Step 6: Make the Change Reboot-Save

To make the change survive a reboot, we edit /etc/fstab as follows:

$ sudo vi /etc/fstab
/swapfile swap swap defaults 0 0 # append this line

Instead of using an editor, the step can be automated as follows:

$ cat /etc/fstab | grep -q swapfile || echo "/swapfile swap swap defaults 0 0" | sudo tee -a /etc/fstab

Step 7: Verify after Reboot

Verify that the swap is still enabled after reboot:

$ sudo reboot

Reconnect after some minutes and:

$ free -h
              total        used        free      shared  buff/cache   available
Mem:           991M         81M        626M         12M        283M        737M
Swap:          2.0G          0B        2.0G


Leave a Reply