Adding Swap Memory to Centos/RHEL/Amazon Linux Servers

A quick guide on adding swap memory. Particularly useful if you run very small servers that crash due to lack of memory.

Typically you only want to use swap to buffer against memory spikes, not to run your application out of. If you consistently use too much memory, get a bigger server.

This guide is used an tested on the RHEL family of Operating Systems. This should work on most other Unix/Linux OS.

How much swap do I need?
RAMSwap Space
2GB or less2x the RAM
2GB to 32GB4 GB + (RAM – 2 GB)
32GB or more1x the RAM
Taken from AWS Knowledge Center Guidelines
Step 1: Create Swap file

The swap file is the size you have calculated previously. Edit the bs and count fields to change the sizes. Typically if you are using swap you don’t have much memory and probably will only want to change the count.

This creates a 2GB file for a 1GB RAM server. (Such as an AWS t3a.micro, or an Azure B1s)

sudo dd if=/dev/zero of=/swapfile bs=128M count=16
Step 2: Set permissions on the file
sudo chmod 600 /swapfile
Step 3: Make it a swap file
sudo mkswap /swapfile
Step 4: Turn on the swap
sudo swapon /swapfile
Step 5: Add it to the fstab config to make it persist on boot
sudo vim /etc/fstab

And add below the other entries:

/swapfile swap swap defaults 0 0

And save the file.

Step 6: Check the swap is enabled:
sudo swapon -s


free -h

And there you have it, you should now have working swap on your server. Let me know if any of this didn’t work for you either in the comments or via the Contact page.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s