Enable swap partition on Linux
If a server has RAM less than 1 GB or uses resource heavy services, it would be a good idea to enable swap space as the RAM may be exhausted here. This article records how I enable Swap on Linux.
What is swap?
From All about Linux swap space:
Linux divides its physical RAM (random access memory) into chucks of memory called pages. Swapping is the process whereby a page of memory is copied to the preconfigured space on the hard disk, called swap space, to free up that page of memory. The combined sizes of the physical memory and the swap space is the amount of virtual memory available.
Confirm if swap is enabled
Run free -h
. Swap is already enabled if its value is not 0.
Generate swapfile
Here is an example of creating 1 GB swap. bs
indicates the unit and count
stands for the size.
sudo dd if=/dev/zero of=/var/swapfile bs=1M count=1024
Create and activate swapfile
# create swapfile
sudo mkswap /var/swapfile
# activate swapfile
sudo swapon /var/swapfile
Then, run free -h
to see if the swap works.
Activate swap space automatically when reboot
echo "/var/swapfile swap swap defaults 0 0" >> /etc/fstab
or just add /var/swapfile swap swap defaults 0 0
into /etc/fstab
.