🐧Linux basics: SWAP file
19-05-2024
Swap is a portion of the servers hard drive which is allocated to temporarily hold data that is not currently used by the server RAM. It acts as additional virtual memory for when the physical RAM is full.
I will be adding 4GB swap to my Ubuntu instance with 8GB RAM.
Check if any swap space is currently enabled on the server
sudo swapon --showIf there's no output on your terminal, it means no swap space is active on the server.
Decide on the size of the swap file you want to create
sudo fallocate -l 4G /swapfileSecure the swap file
sudo chmod 600 /swapfileSet the swap area
sudo mkswap /swapfileEnable the swap file
sudo swapon /swapfileVerify that the swap is active
sudo swapon --show
To ensure the swap file is used on boot, you need to add it to /etc/fstab.
Backup the current file
sudo cp /etc/fstab /etc/fstab.bakAdd the swap file to the
/etc/fstabfile:
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstabSet the swappiness value (Optional)
Swappiness controls how much your server makes use of the allocated swap space. Lower values results in the server using swap less often, which can make it faster. Higher values make the system use swap more often, which can keep more RAM free.
sudo sysctl vm.swappiness=10echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.confCheck the server RAM and SWAP
free -h
Enabling swap allows you to fine-tune how your system balances performance and processes that require memory in either form of RAM or Swap. Having swap space is a practical strategy for maintaining smooth and efficient operations on your Linux server.
Last updated