Set up Swap Memory on Linux Server
Find out how to create and set up a swap file, and how much swap space you need.
Create Swap
Swap memory uses storage space on your server to act as additional memory when your RAM is full. Without swap, your server might slow down or freeze if the RAM runs out. Downsides are that swap is slower than RAM and takes up storage space, so you can’t use it for storing files. Swap can also wear down storage drive over time, though this happens slowly.
- Create a swap file:
sudo dd if=/dev/zero of=/swapfile bs=1M count=8192
count=8192
creates a 8GB (8192MB) swap file. Change the number to create a bigger or smaller swap file. For example, count=4096
would create a 4GB (4096MB) swap file.
- Set permissions:
sudo chmod 600 /swapfile
- Format swap file for use:
sudo mkswap /swapfile
- Start swap file:
sudo swapon /swapfile
- Display swap:
sudo swapon --show
- Make the swap file permanent.
Open /etc/fstab
file:
sudo nano /etc/fstab
Add the folliowing line at the end of the file:
/swapfile none swap sw 0 0
Your server will automatically enable swap every time it boots up.
TIPYou can use
free -m
andhtop
command to check your RAM and swap memory usage.
Delete Swap
Run the following commands to delete the swap file and start over if you have any issues creating the swap file.
sudo swapoff /swapfile
sudo rm /swapfile
Resize Swap
- Delete swap file:
sudo swapoff /swapfile
sudo rm /swapfile
- Create a new swap file.
Recommended Swap Size
RAM Size | Recmmended Swap Size |
---|---|
~4GB | 2x the size of RAM |
4~8GB | Equal to the size of RAM |
8~16GB | 1~1.5x the size of RAM |
16GB | 1x the size of RAM or less |
This is a general guideline. The actual swap size needed depends on your server’s workload.