Guide to Creating Swap Space on Ubuntu 16.04 / 17.04

First check if the system has any swap configured.

swapon --show

If the output is blank, there is no swap configured so we can continue with this guide.

1. Create a Swap File

We will use the fallocate program to create a swap file. Best practice is to create a swap file double the amount of your RAM. If you have 512MB of RAM, create a 1GB swap file.

sudo fallocate -l 1G /swapfile

Now check if the file was created.

ls -lh /swapfile

If it was created correctly, you should see something like:

-rw-r--r-- 1 root root 1.0G May  6 20:41 /swapfile

2. Configure Swap File

Make the swap file only accessible to root.

sudo chmod 600 /swapfile

Mark the file as a swap file.

sudo mkswap /swapfile

If it was successful, you should see something like

Setting up swapspace version 1, size = 1024 MiB (1073737728 bytes)
no label, UUID=801104b5-1967-458d-a564-8d63e7a24403

Finally we will tell the system to start using our new swap file,

sudo swapon /swapfile

To verify that the swap is now available type:

sudo swapon --show

Result:

NAME      TYPE  SIZE USED PRIO
/swapfile file 1024M   0B   -1

We can also run the following to see our new swap file alongside physical memory

free -h

Result:

              total        used        free      shared  buff/cache   available
Mem:           488M        218M        124M         37M        145M        203M
Swap:          1.0G          0B        1.0G

3. Make it Persistent

This swap will only last until next reboot. In order to make it permanent, we will add it to the /etc/fstab file.

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

4. Swap Settings

For a server, you should change the swappiness value to 10.

sudo sysctl vm.swappiness=10

Now change the vfs_cache_pressure value to 50.

sudo sysctl vm.vfs_cache_pressure=50

To make these two settings persist after next reboot, edit the following file:

sudo nano /etc/sysctl.conf

Add this to the bottom.

/etc/sysctl.conf
vm.swappiness=10
vm.vfs_cache_pressure=50

Save file and exit. (Press CTRL + X, press Y and then press ENTER)

A useful way to keep an eye on your swap usage is to run htop. See: Better system monitoring with htop

  • 0 Users Found This Useful
Was this answer helpful?

Related Articles

How To Install and Use Docker on Ubuntu 16.04

Introduction Docker is an application that makes it simple and easy to run application processes...

Change Main IP of the server :: Vesta Panel

If we are changing the main IP of a server installed with Vesta panel, we can use the following...

cPanel: Apache-FastCGI Data Timeout Error

If you are using a cPanel server and have FastCGI enabled in Apache, you might be facing the...

Domainkey installer in cPanel

You can use the following cPanel script to install domainkey for an account...

Email issues :: Common Troubleshooting Steps

Here I will discuss some common errors and their solution: We are using a mail relay setup for...