266 words
1 minutes
Set up Swap Memory on Linux Server

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.

  1. 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.

  1. Set permissions:
sudo chmod 600 /swapfile
  1. Format swap file for use:
sudo mkswap /swapfile
  1. Start swap file:
sudo swapon /swapfile
  1. Display swap:
sudo swapon --show
  1. 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.

TIP

You can use free -m and htop 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#

  1. Delete swap file:
sudo swapoff /swapfile
sudo rm /swapfile
  1. Create a new swap file.
RAM SizeRecmmended Swap Size
~4GB2x the size of RAM
4~8GBEqual to the size of RAM
8~16GB1~1.5x the size of RAM
16GB1x the size of RAM or less

This is a general guideline. The actual swap size needed depends on your server’s workload.

Set up Swap Memory on Linux Server
https://blog.juyoun.gg/posts/en/2025/01/25/
Author
Jay
Published at
2025-01-25
License
CC BY