KUDOS

Setting up swap space on Ubuntu

2 min read

What is a swap file?

A swap file is a space on your hard disk that acts as virtual memory. If your memory is used to capacity it can be used as backup memory. If you have 16GB of RAM and an 8GB swap file you have 24GB of memory.

Why Would I need swap space?

In this case I have a small cloud web server that consistently crashes due to running out of memory. I don’t want to upgrade to a larger server as it would cost more.

Checking if you already have a swap file

You can check if you already have swap space by running the free command.

$ free -h

output:
        total  used   free   shared  buff/cache  available
Mem:    978M   345M   124M   59M     509M        415M
Swap:   0      0      0

As you can see there is no swap space active. We have 1Gb of memory and 415m available.

Check how much space you currently have

$ df -h

output:
Filesystem  Size  Used  Avail  Use%  Mounted on
/dev/xvda1  7.7G  5.1G  2.7G   66%   /

As you can see we have 2.7Gb of free space.

Create a swap file

Lets create a 1Gb swap file using fallocate.

$ sudo fallocate -l 1G /swap
$ sudo chmod 600 /swap
$ ls -lh /swap

Output:
-rw------- 1 root root 1.0G May 27 10:14 /swap

Enable the swap file

$ sudo mkswap /swap

output:
Setting up swapspace version 1, size = 1024 MiB (1073737728 bytes)
no label, UUID=6e965805-2ab9-450f-aed6-577e74089dbf

And make sure it is setup correctly.

$ free -h

output:
        total  used   free   shared  buff/cache  available
Mem:    978M   345M   124M   59M     509M        415M
Swap:   1.0G      0   1.0G

Make the swap file permanent

Make it permanent by adding the following to the bottom of your /etc/fstab file.

/swap none swap sw 0 0

Conclusion

If you are able to scale your server vertically it is recommended. There are issues with hardware degradation using this method, especially with SSDs. However, this method can be especially useful for micro-servers on the big cloud platforms if you are consistently running into “out of memory” issues.


SHARE

Sign up to our newsletter

Give your inbox a healthy dose of inspiration. Keep up to date with our monthly newsletter.