How to setup swap file on Linux Server
When memory is full on a Linux server, some services like MariaDB/MySQL may shut down automatically. To prevent this, you can add extra virtual memory using a swap file. This guide shows how to create a swap file on a Linux server with low RAM.
What is a Swap File?
During Linux installation, the system may ask how much space to allocate for swap. Swap is a form of virtual memory. When physical RAM is full, Linux moves inactive pages to swap space. Total virtual memory = RAM + swap.
Swap can be a swap partition, a swap file, or both. On Windows, swap is usually just a file on disk. Most Linux distros create a swap partition automatically.
Check Current Swap Usage
Use the following command to check your system's current swap:
swapon --show
This will show:
- Number of swap files/partitions
- Size of each
- Current usage
- Priority of each swap device
Higher priority means the system will use that swap first.
How to Create a Swap File
On a VPS with a single root partition, you can't create a new partition for swap, but you can create a swap file instead.
Step 1: Create the Swap File
To create a 512MB swap file:
sudo fallocate -l 512M /swapfile
Or for 1GB:
sudo fallocate -l 1G /swapfile
Step 2: Set Permissions
sudo chmod 600 /swapfile
Step 3: Format the File
sudo mkswap /swapfile
Example output:
Setting up swapspace version 1, size = 524284 KiB
no label, UUID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Step 4: Enable the Swap File
sudo swapon /swapfile
Step 5: Verify It’s Working
sudo swapon --show
Example output:
NAME TYPE SIZE USED PRIO
/swapfile file 512M 132K -1
Step 6: Enable on Boot
Add this line to your /etc/fstab
file:
/swapfile none swap defaults 0 0

Note: Use the Tab key (not spaces) to separate each column in /etc/fstab
.
Tags: