Menu
User

DropVPS Team

Writer: Cooper Reagan

How to Create a Swap File on Ubuntu VPS

How to Create a Swap File on Ubuntu VPS

Publication Date

05/15/2026

Category

Articles

Reading Time

2 Min

Table of Contents

Swap space on Ubuntu helps prevent memory-related crashes by allowing the server to temporarily move inactive data from RAM to disk. On smaller VPS plans, adding swap can improve stability during traffic spikes or heavy background tasks.

Many developers configure swap immediately after deploying a new Linux VPS server, especially on systems running databases, control panels, or multiple services with limited RAM.

Step 1: Check Existing Swap Space

Connect to the server using SSH:

ssh root@your_server_ip

Check whether swap is already enabled:

swapon --show

You can also verify memory usage:

free -h

If no swap appears in the output, continue with the next steps.

Step 2: Create a Swap File

Create a 2GB swap file:

fallocate -l 2G /swapfile

If fallocate is unavailable, use:

dd if=/dev/zero of=/swapfile bs=1M count=2048

Verify the file size:

ls -lh /swapfile

Step 3: Set Correct Permissions

Restrict access to the swap file:

chmod 600 /swapfile

This prevents normal users from reading swap data.

Step 4: Format the Swap File

Convert the file into swap format:

mkswap /swapfile

The output should confirm that swap space has been created successfully.

Step 5: Enable Swap

Activate the swap file:

swapon /swapfile

Check if swap is active:

swapon --show free -h

Step 6: Make Swap Persistent After Reboot

Open the filesystem table:

nano /etc/fstab

Add this line at the bottom:

/swapfile none swap sw 0 0

Save and exit Nano:

CTRL + X Y ENTER

Step 7: Optimize Swap Settings

Adjust the swappiness value:

sysctl vm.swappiness=10

To make it permanent:

echo "vm.swappiness=10" >> /etc/sysctl.conf

Lower swappiness values help Ubuntu prioritize RAM usage before using disk swap.

After enabling swap, the Ubuntu VPS can handle memory pressure more efficiently and reduce the risk of random service crashes caused by insufficient RAM.

Linux VPS
U
Loading...

Related Posts