Resizing Swap File with Bash

[vc_row][vc_column width=”1/2″][vc_column_text]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.[/vc_column_text][/vc_column][vc_column width=”1/2″][vc_column_text]

echo "====== Current Swap ======"
sudo swapon -s
echo "====== Turning Off Swap ======"
sudo swapoff /swapfile
echo "====== Allocating 4GB Swap ======"
sudo fallocate -l 4G /swapfile
echo "====== Making Swap ======"
sudo mkswap /swapfile
echo "====== Setting Permissions to Root Only  ======"
sudo chmod 600 /swapfile
echo "====== Turning On Swap ======"
sudo swapon /swapfile
echo "====== Current Swap ======"
sudo swapon -s
echo "====== Done! ======"
echo $(date)


Share Post :


  • Denis Trofimov
    June 25, 2018 at 5:38 am 

    I have good results on my Ubuntu 17.04 following your advice from this blogpost.
    A have cited it here .

    • Arian Acosta
      July 29, 2018 at 8:30 am 

      Fantastic! Thanks for sharing!

Leave a Reply