Creating a Swap File in Linux

To Swap or Not to Swap

A swap file is a location on your disk that the Linux kernel can use to provide extra memory when your system is running low. Most Linux distribution installers will create a partition for this purpose, but this is a waste of space on most modern systems, especially when using SSD drives with limited space.

That doesn’t mean you should disable swap entirely, though. Not having a swap file means that programs may occasionally be terminated for lack of free memory even in moderately loaded systems. Rather than dedicating an entire partition to this purpose, a swap file is perfectly suitable and easy to configure without having to repartition your drive.

You May Already Be Swapping

Before creating a swap file, you should check to see if there is any active swap file or partition. To do this, run a Terminal or SSH in to your machine and run:


If nothing is returned, then there is no swap file. If so, the details of the file or partition will be shown.

Creating the Swap File

If you have plenty of memory, I’d recommend creating a 2 GB swap file. It’s what I usually setup on virtual servers. To do this, run:

sudo dd if=/dev/zero of=/swap bs=64M count=32
sudo chmod 0600 /swap
sudo mkswap /swap

Note in this case I’m telling the “dd” command to write 64 MB of zeros 32 times, which totals 2097120 bytes, or 2 GB. If you wanted to use a 1 GB file, you would specify 16 for the count instead of 32.

The next step is to add this swap file to the /etc/fstab file. This will tell Linux to activate the file upon boot. To do so, run:

sudo echo "/swap swap swap defaults 0 0" >> /etc/fstab

Note: If you aren’t copying and pasting the line above, it is imperative that you double check your typing. If you don’t use >> near the end, it could clobber your /etc/fstab file and create massive problems. The >> tells echo to add it to the end, whereas > would tell it to overwrite the file. Be careful!

To activate the swap file, run:

swapon -a

If you run the swapon command again by itself without any parameters, you’ll note the new swap file is now active.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s