Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Problem

You may want/need to create and enable a swap file on your Linux machine (or server).  For example, on some AWS EC2 instances you don't get ephemeral (temporary) storage disks that can be used for swap, so you might want to create a swap file on the main EBS volume to alleviate potential memory issues.

Solution

You can create a swap file on your Linux server via a terminal.  Note, you'll need sudo access for this.

First let's check if any swap files have already been enabled:

Code Block
languagebash
sudo swapon -s

Output will list any swap files already active.  To turn off all swap devices use [sudo swapoff -a].

The following will create and enable a 8GB swap file at /swapfile

Code Block
languagebash
sudo dd if=/dev/zero of=/swapfile bs=1M count=8120
sudo mkswap /swapfile
sudo chmod 600 /swapfile
sudo swapon /swapfile

Making swap persistent

Doing the above will simply enable swap.  After a server reboot swap won't be enabled.  Do the following to make it persistent:

Code Block
languagebash
sudo cp /etc/fstab /etc/fstab.backup
echo '/swapfile none swap defaults 0 0' | sudo tee -a /etc/fstab

Now make sure you run (see below) which will check for errors.  If nothing (no errors) show then you should be good to go.  If errors, don't reboot until you fix (or restore from backup).

Code Block
languagebash
sudo mount -a

References

  1. https://stackoverflow.com/questions/17173972/how-do-you-add-swap-to-an-ec2-instance

Content by Label
showLabelsfalse
max5
spacesTKB
showSpacefalse
sortmodified
reversetrue
typepage
cqllabel in ("swap","ec2") and type = "page" and space = "TKB"
labelsec2 swap

...

hiddentrue

...

Article migrated to https://me.jaytaala.com/create-and-enable-swap-file-on-linux/