How to Add Swap Space on Ubuntu (5GB Example)

Published: (March 16, 2026 at 06:38 AM EDT)
3 min read
Source: Dev.to

Source: Dev.to

Why Swap Matters

Swap is disk space that your OS uses as overflow when physical RAM fills up. Without it, the kernel may start killing processes (the dreaded OOM killer) when memory is exhausted. With swap, the system degrades gracefully instead of crashing.

My setup: 7.57 GB RAM, 0 KB swap. Adding 5 GB swap gives the system room to breathe under heavy loads.

Steps to Add Swap

Step 1: Create the Swap File

sudo fallocate -l 5G /swapfile

If fallocate isn’t available, use dd as a fallback:

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

Step 2: Lock Down Permissions

sudo chmod 600 /swapfile

This ensures only root can read/write the swap file, preventing potential data leaks.

Step 3: Format as Swap

sudo mkswap /swapfile

Typical output:

Setting up swapspace version 1, size = 5 GiB (5368705024 bytes)
no label, UUID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

Step 4: Enable the Swap

sudo swapon /swapfile

Step 5: Make It Permanent

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Appending this line to /etc/fstab ensures the swap is activated at boot.

Step 6: Verify

free -h

You should see something like:

               total        used        free      shared  buff/cache   available
Mem:           7.5Gi       3.2Gi       1.1Gi       512Mi       3.2Gi       3.6Gi
Swap:          5.0Gi          0B       5.0Gi

Swap is now active. ✅

Bonus: Tune Swappiness

Ubuntu defaults to vm.swappiness=60, which starts using swap when RAM usage hits ~40 %. For desktops or workstations with ample RAM, a lower value is preferable.

Check the current value

cat /proc/sys/vm/swappiness

Set it to 10 (apply immediately)

sudo sysctl vm.swappiness=10

Make it permanent

echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf

Swappiness Reference

ValueBehavior
0Avoid swap entirely (use only in emergencies)
10Prefer RAM strongly — great for desktops/workstations
60Ubuntu default — balanced
100Swap aggressively

For most desktop users with 4 GB+ RAM, 10 is the sweet spot.

Quick Summary

# 1. Create
sudo fallocate -l 5G /swapfile

# 2. Secure
sudo chmod 600 /swapfile

# 3. Format
sudo mkswap /swapfile

# 4. Enable
sudo swapon /swapfile

# 5. Persist
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

# 6. Verify
free -h

# Bonus: tune swappiness
sudo sysctl vm.swappiness=10
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
0 views
Back to Blog

Related posts

Read more »

Travigo

Travel as fast as you speak with Gemini! Where live agents meet immersive storytelling & 3D navigation. This project was created for entering the Gemini Live Ag...

Micro games

Hey Gamers! 👾 As part of the Rapid Games Prototyping module, we are tasked with reviewing a peer's game. The challenge is to analyse a prototype built in just...