Add a swap file

A few days back, nginx on one of our Amazon t1.micro instance started logging 110 Connection Timeout after a long drag of high CPU usage (>90%). Adding a swap file helped to get rid of this error and its been running wonderfully now.

Swap space is not a strict requirement but it might be a good idea to increase your virtual memory for certain applications.

  1. To see what swap files/partitions are active on your system, run the swapon command with the -s flag

    $ swapon -s

  2. Create a zero bytefile of the desired size using the dd command.

    $ dd if=/dev/zero of=/swapfile bs=1024 count=1048576

    Count should be the number of KiB you want the swap file to have. I'm setting it to 1GiB

  3. Next, create it a swap file using the mkswap command

    $ mkswap /swapfile

  4. Tell your system to actively use this newly created swapfile using the swapon command

    $ swapon /swapfile

  5. Add an entry to /etc/fstab preserving this for reboots

    /swapfile none swap sw 0 0

  6. Verify that your swap is active

    $ swapon -s

Thats it! You should now have working swapfile.