in Sysadmin

Enabling swap in Linux

In Linux, when physical memory (RAM) is full, inactive pages in memory are moved to the swap. Swap space is located on hard drive, which is significantly slower than RAM. While swap space can help machines with a small amount of RAM, it should not be considered a replacement for more RAM. However, it’s very useful when you need a little bit more RAM for a brief piece of time, like compiling software etc.

Many VPS providers (like Digital Ocean) don’t enable swap automatically, and you need to enable it by yourself. Here’s how:

First, create swap file. This creates /swap with size of 512MB with correct permissions:

sudo dd if=/dev/zero of=/swap bs=1024 count=512k
sudo chown root:root /swap
sudo chmod 0600 /swap

What size should be swap? If unsure, read this.
Prepare swap and enable it:

sudo mkswap /swap
sudo swapon /swap

Swap will be enabled until you reboot your server (VPS). If you want it to be persistent, add following line into /etc/fstab:

/swap none swap sw 0 0

Additional reads:

How To Add Swap on Ubuntu 12.04
How To Add Swap on Ubuntu 14.04

Write a Comment


This site uses Akismet to reduce spam. Learn how your comment data is processed.