Resizing Swap File with Bash

Linux machines use a disk partition called swap as an extension of memory. Properly setting the swap size is particularly important for small VPS nodes. For instance, I spawned a couple of droplets on DigitalOcean with 2GB of RAM running MySQL, and sometimes during peak hours or complex queries, the mysqld service would simply stop. If you looked at the memory usage history (in New Relic for example) you would see a big spike and then a drop.

Increment swap size if the memory peaks are infrequent. Increment RAM if most of the time the memory usage is high.

Generally speaking, the recommended size for a swap file is 2X the amount of RAM, but you can make it as big as you need. Remember that this is not a substitute for memory because performance is much worse since things are stored in the disk.

I’ve created a simple bash script that increments the swap file to 4GB and tested it on Ubuntu 16.04.

This can be run line by line or a bash script, but I use it to make headless installations.

Share Post :

  • Denis Trofimov

    I have good results on my Ubuntu 17.04 following your advice from this blogpost.
    A have cited it here https://askubuntu.com/a/1049496/648602 .
    Thanks!

    • Arian Acosta

      Fantastic! Thanks for sharing!