Add swap space on Ubuntu
Swap is disk space the kernel uses as overflow memory when RAM is full, which can stop small servers from killing processes.
- Updated Nov 27, 2026
- Markdown
Add a 2 GB swap file to an Ubuntu server and make it survive reboots.
- An Ubuntu server with sudo access
- A few GB of free disk space
To add swap space on Ubuntu, you create a file, format it with mkswap, enable it with swapon and list it in /etc/fstab. A small server with 1 GB of RAM runs fine until a build, a database import or a traffic spike pushes memory past the limit. Without swap, the kernel’s out-of-memory killer ends a process, often your database or app, with no warning. A swap file gives the kernel a place to move rarely used memory pages so the busy ones can stay in RAM.
How it works#
Memory is split into pages. When RAM fills up, the kernel can write pages that have not been used recently to swap on disk and reuse the RAM. If a program needs that page again, the kernel reads it back. That read is far slower than RAM, which is why heavy swapping makes a server feel frozen.
So swap does two things in practice:
- It gives you headroom for short spikes, so a brief peak does not kill a process.
- It lets the kernel push idle pages out, which can leave more RAM for file caching.
It does not make a memory-hungry app fast. If free -h shows swap in constant use and the machine is slow, the real fix is more RAM or a smaller workload.
Swap can be a partition or a file. A file is easier on a cloud server because you do not repartition anything. The kernel has three requirements: the file must be on a filesystem that supports it, be readable only by root, and be formatted with mkswap. The swappiness setting (0 to 100, with 60 as the usual default) controls how eagerly the kernel uses swap.
Step 1: Check current swap#
swapon --show
free -hWhat you should see: if swapon --show prints nothing, there is no swap, and free -h shows 0B on the Swap: row. If it already lists an entry, you may not need more. Also check free disk space with df -h /.
Step 2: Create the file#
This example makes a 2 GB file at /swapfile:
sudo fallocate -l 2G /swapfile-l 2G sets the length. What you should see: no output. If fallocate fails on your filesystem, use this instead, which writes every block and takes a bit longer:
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progressHere bs=1M count=2048 means 2048 blocks of 1 MiB.
Step 3: Lock down permissions#
Only root should read swap, since it can contain memory contents (see Linux file permissions explained):
sudo chmod 600 /swapfileWhat you should see: no output. Verify with ls -lh /swapfile, which should start with -rw-------.
Step 4: Format and enable it#
Warning:
mkswapoverwrites the target. Make sure the path is your new swap file and not an existing file or disk.
sudo mkswap /swapfile
sudo swapon /swapfileWhat you should see: mkswap prints Setting up swapspace with the size and a UUID. swapon prints nothing when it works.
Step 5: Make it permanent#
Back up fstab, then add one line:
sudo cp /etc/fstab /etc/fstab.bak
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstabThe fields are file, mount point (none for swap), type, options and two dump/check flags. What you should see: the line printed back by tee. A typo in /etc/fstab can cause boot problems, so check it with cat /etc/fstab.
Check it worked#
swapon --show
free -hswapon --show should list /swapfile with type file and the size you chose. free -h should show the same total on the Swap: row. Reboot and run the commands again to confirm it persists. To test the fstab line without rebooting, run sudo swapoff /swapfile and then sudo swapon -a, which enables everything listed in fstab.
Edge cases and gotchas#
- Some filesystems need extra care. Btrfs and ZFS do not treat a plain
fallocatefile like ext4 does. On Btrfs, a swap file has special requirements, so follow the filesystem’s own documentation rather than this lesson. - A sparse file triggers a “holes” error. If
swaponsays the swapfile has holes,fallocateproduced a file with unallocated blocks. Remove it and recreate it withdd. - Swap can already exist. Some images ship with a swap file such as
/swap.imgor a swap partition. Adding a second one wastes disk. Check step 1 first. - Low disk space is a real risk. A 2 GB swap file on a 10 GB disk takes a fifth of it. Docker images and logs can fill the rest, so leave room.
- Container-style hosts may refuse swap. On virtualisation that shares the host kernel,
swaponcan fail with a permission or operation error. That is a host limit, not a mistake in your commands. - Swappiness is a trade-off. Lower values make the kernel prefer RAM and use swap later. Set it for the current boot with
sudo sysctl vm.swappiness=10. To make it persistent, putvm.swappiness=10in a file under/etc/sysctl.d/. - A swap file is not a fix for a leak. If a process grows without limit, swap only delays the crash and slows the machine meanwhile.
Troubleshooting#
| Symptom | Likely cause | Fix |
|---|---|---|
swapon: /swapfile: insecure permissions 0644, 0600 suggested. | File readable by others | Run sudo chmod 600 /swapfile |
fallocate failed: Operation not supported | Filesystem does not support fallocate | Create the file with dd instead |
No space left on device | Disk too full for the size | Pick a smaller size or free space (df -h /) |
swapon: /swapfile: swapon failed: Invalid argument | File not formatted, or it has holes | Run mkswap on it, or recreate it with dd |
| Swap gone after reboot | fstab line missing or mistyped | Re-check the line in /etc/fstab, then sudo swapon -a |
| Server is slow with swap in use | The workload needs more RAM | Check free -h and top, reduce load or use a bigger server |
swapon: /swapfile: read swap header failed | The file was never formatted with mkswap, or is truncated | Run sudo mkswap /swapfile on it, or recreate the file |
Swap is listed but free -h shows 0B used and the app still dies | The process hit a per-container or per-service memory limit | Check cgroup or Docker memory limits, swap does not raise them |
| The server boots slowly after a bad fstab line | The line has a typo | Boot the console, fix /etc/fstab from the .bak copy |
To remove swap later, run sudo swapoff /swapfile, delete the fstab line, then sudo rm /swapfile.
Real-world scenario#
A 1 GB server runs a Node app and a Postgres container. Every few days the app disappears. dmesg shows Out of memory: Killed process and the name of the app.
You run free -h and see Swap: 0B. You create a 2 GB /swapfile, run chmod 600, mkswap and swapon, then add the line to /etc/fstab. swapon --show lists the file.
The next traffic spike pushes memory over the limit, but the kernel moves idle pages to disk instead of killing a process. The app slows for a minute and recovers. Weeks later free -h still shows swap in use, which tells you the real fix is a bigger plan, and swap bought you the time to decide.
Quick reference#
| Task | Command |
|---|---|
| Show swap | swapon --show and free -h |
| Create | sudo fallocate -l 2G /swapfile |
| Lock down | sudo chmod 600 /swapfile |
| Format and enable | sudo mkswap /swapfile && sudo swapon /swapfile |
| Persist | /swapfile none swap sw 0 0 in /etc/fstab |
| Remove | sudo swapoff /swapfile, delete the fstab line, sudo rm /swapfile |
Security and safety notes#
- Check the path before
mkswap; it erases whatever it is pointed at. - Back up
/etc/fstabbefore editing it, because a broken line can slow or stop booting.
Related lessons#
- Check disk, memory and CPU usage: read the numbers before and after adding swap
- Essential Linux commands for servers: the tools used here
- Linux file permissions explained: why mode 600 matters
- Read container logs: confirm whether a container was killed for memory
Next#
Move files to and from the server with Copy files with scp and rsync.
Check what you learned
Frequently asked questions
How big should the swap file be?
A common starting point is about the same size as RAM on small servers, less on large ones. Pick a size that fits your free disk space.
Is swap a replacement for more RAM?
No. Disk is much slower than memory, so heavy swapping makes a server crawl. Swap is a safety net, not extra speed.
Why did my app get killed even though I have swap?
Swap only delays the problem. If memory and swap are both used up, the kernel's out-of-memory killer ends a process. Check dmesg for Out of memory messages and consider a bigger server or lower memory limits.
Can I add swap on any VPS?
Most full virtual machines allow it. Some container-style hosts do not let you create swap inside the guest, and the swapon command then fails. Ask your provider if you hit that.
Keep going: guides and tutorials
- Install a Self-Hosted PaaS on Your Own Server in Five Minutes One installer download, one setup token, one sample app. The full Levelrail install on a fresh Linux server, with the checks and the fixes.
- Manage Secrets Self-Hosted: Env Vars and Master Key Rotation Set env vars and encrypted secrets on a self-hosted server, apply changes safely, and rotate the master key with no downtime without locking yourself out.