Skip to content

Instantly share code, notes, and snippets.

@HendrikPetertje
Last active January 26, 2021 07:52
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save HendrikPetertje/7986434 to your computer and use it in GitHub Desktop.
Create a swap file in ubuntu

Is your digitalocean server getting overheated on memory when more and more visitors visit your site while cpu usage stays somehow normal? Chances are that you are not using a swap partition or file on your server. Swap is linux's way of pagefiling. When the server runs out of RAM it will start saving things to a swap partition.

In this small guide I will describe the creation of a swap partition under Linux.

You could create a disk image file (like a daemontools virtual disk) that is filled with zeros. 1GB of zero's in this case:

dd if=/dev/zero of=/mnt/swap.img bs=1M count=1024
But don't do this, keep reading ;)

But this has some unnesesairities. First you are dragging around a file on your disks and secondly every "bit" of your disk image file get's rewritten. Later your swap file will be a host to loose code and mem-dumps. that disk of zero's will soon change into a jungle of zero's and ones. Use fallocate instead to allocate the beginning of the file and the end of it. The file has content already since it is not "zero'd", but being swap that doesn't matter.

fallocate -l 1024M /mnt/swap.img

Format the file to create a swap device (the partition library get's added)

mkswap /mnt/swap.img

Adding the swap to the running system:

swapon /mnt/swap.img

Make it permanent, edit /etc/fstab and add the following entry:

/mnt/swap.img  none  swap  sw  0 0

Now every time you boot your server it will load the swap file.

Good luck!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment