Most people running a Linux system would agree that you should set up swap. According to the poll below, only 28% believe that no swap is required. And I think that they are misguided. Always put some swap on your system. You’ll never regret it.
There are two approaches to adding swap to your system:
- a separate swap partition or
- a swap file on an existing partition.
Swap Partition
You can set up an entire separate partition which is dedicated to swap.
Suppose, for example, that your swap partition will be at /dev/xvdb
.
PARTITION="/dev/xvdb"
Set up a swap area on the partition.
sudo mkswap $PARTITION
And then turn the swap on
sudo swapon $PARTITION
Check that you have swap space available with free
.
Swap File
A somewhat simpler approach is to just set up one or more swap files.
SWAPFILE="/var/swap"
How big do you want the swap file to be? The units can be M
(megabyte), G
(gigabyte) or T
(terabyte).
SIZE=2G
Create the swap file.
sudo fallocate -l $SIZE $SWAPFILE
If you don’t have fallocate
then you can go Old School.
sudo dd if=/dev/zero of=$SWAPFILE bs=1M count=2048
Next, set the mode of the swap file, format it as swap space and turn it on.
sudo chmod 600 $SWAPFILE
sudo /sbin/mkswap $SWAPFILE
sudo /sbin/swapon $SWAPFILE
You’ll probably want the swap to be present after rebook, so add it to your /etc/fstab
.
/var/swap swap swap defaults 0 0
Turning Swap On & Off
You can easily enable or disable swap.
# Disable all swap
sudo swapoff -a
# Enable all swap
sudo swapon -a