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


/swapfile file 1024M   0B   -1

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

free -h


              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.


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

Let me know in the comments if this helped. Follow me @DevAnswers or buy me a beer 🍺


Your email address will not be published. Required fields are marked *

We use Markdown to style comments, like on Github and Reddit.
To do a line break, type two spaces after the sentence.
You can add inline code by wrapping it in backticks: `code here`

    To do an entire block of code  
    type four spaces before the line
    and it will appear in a block like this.
    <-- four empty spaces