How Do You Create Swap Space on a Linux Server Running in the Cloud?

Problem scenario
You have sufficient hard disk space.  But your applications are memory constrained on your Linux server.  You cannot add more RAM.  How do you create swap space on your Linux server (to create virtual memory)?

Solution
Overview
We consider virtual memory to be a hybrid of RAM "and disk space that running processes can use. Swap space is the portion of virtual memory that is on the hard disk, used when RAM is full." The quoted section was taken from StackOverflow.

Procedures
These directions to have been tested to work on a Google Cloud Platform Debian server, an AWS Ubuntu server, and an AWS RedHat Enterprise Linux (RHEL) server.  (If you want a script to do this, see this posting.) They will work on a server in Azure too.

Warning: This will create a swap space that can be read by other processes.  You may want to use the optional step at the end to make it more secure.

1.a.  This is optional.  You may want to run this command:

top | grep Swap # This is an optional step.  Cancel out after you see a line of results.

1.b.  If you are running SUSE or a RedHat derivative of Linux (CentOS/RHEL/Fedora), run this:
sudo dd if=/dev/zero of=/mnt/2GB.swap count=2048 bs=1MiB

If you are running Debian/Ubuntu Linux, run this:
sudo fallocate -l 2G /mnt/2GB.swap

2.  Run these commands:
sudo mkswap /mnt/2GB.swap
sudo swapon /mnt/2GB.swap

3.  Update the /etc/fstab to have this line (i.e., append it to the file as the lowest line):
/mnt/2GB.swap  none  swap  sw 0  0

4.  Update the /etc/sysctl.conf file to have this stanza at the very end:

vm.swappiness=10

5.  Run this command:  sudo swapon -s

6.  Optional command to make the swap space more secure:  sudo chmod 600 /mnt/2GB.swap

7.  Optional command to check your work and compare it to the first command above:
top | grep Swap # This is an optional step.  Cancel out after you see a line of results.

The above directions were based on RackSpace directions here.

Leave a comment

Your email address will not be published.