How to set swap space for Linux

Recently, I found the memory of my VPS is not enough. So I decide to set a swap space for this VPS to share stress of memory usage.

How to set

Log into your server as root.

1
2
3
4
5
6
sudo swapon --show # check current status of swap
sudo fallocate -l 6G /swapfile # create a swapfile which is 6G large. You can change this size as you like.
sudo chmod 600 /swapfile # change access permissions of swapfile
sudo mkswap /swapfile # set swapfile as swap space
sudo swapon /swapfile # activate swap space
sudo vim /etc/fstab # let swap space mount automatically when reboot
1
/swapfile none swap sw 0 0
1
2
mount -a # if output is nothing, your fstab works fine.
sudo swapon --show # check current status of swap to verify whether the set takes effect.