Linux and servers · Beginner · 12 min
Add swap space to a server with a swap file
By Padding · Updated 18 Nov 2026
Ubuntu 26.04.1 LTS · util-linux 2.41
You will have a 2 GB swap file that is private to root, turned on at every boot from /etc/fstab, tuned with vm.swappiness in a sysctl.d drop-in, and you will know how to remove it cleanly.
On this page
Swap is disk space the kernel can move idle memory pages into when RAM runs short. On a small VPS with 1 GB of RAM and no swap, one memory spike (an apt upgrade, a Composer install, a build step) can make the kernel's out-of-memory killer stop your database or web app. A modest swap file gives the kernel somewhere to put pages that nobody is touching, so the spike passes instead of killing a process.
Swap is not extra RAM. Disk is hundreds to thousands of times slower than memory, so a server that uses swap all day is a server that is too small or has a process leaking memory. Swap buys time and absorbs short peaks; it does not fix a workload that needs more memory than you have.
Many readers start on the smallest plan a local or global provider sells, often 512 MB or 1 GB, to keep the monthly bill predictable. Those plans are where a swap file helps most. In this tutorial you check whether swap is the right fix, create a 2 GB swap file the safe way, make it survive a reboot, tune how eagerly the kernel uses it, look at zram as an alternative, and remove it again.
Step 1 · Decide whether swap is the fix you need
Look at memory, disk and any swap that already exists:
free -h
swapon --show
df -h /free -h prints a Mem: line and a Swap: line. Read the available column on the Mem: line, not free: Linux fills unused RAM with file cache and gives it back on demand, so free is often near zero on a healthy server. swapon --show prints nothing when the server has no swap. Most cloud images ship without any; an Ubuntu Server installed from the ISO usually already has a swap file at /swap.img.
Use this rough guide:
- Add swap if
availabledrops low only during peaks (upgrades, deploys, nightly jobs), or if the kernel log shows the out-of-memory killer firing during those peaks./tutorials/find-what-is-using-memory-and-read-oom-killer-messagesshows how to read those messages. - Do not rely on swap if one process grows steadily until it is killed, or if
availablestays low all day. Find the process or move to a bigger plan; swap only makes that server slow before it falls over. - Size: on a server with up to 4 GB of RAM, a swap file of 1 to 2 GB is plenty. Servers do not hibernate, so you do not need swap the size of RAM.
Check it worked
You can say in one sentence why this server needs swap, for example "it has 1 GB of RAM, no swap, and the OOM killer stopped MySQL during last night's upgrade". If swapon --show already lists a swap file or partition, you do not need a second one; skip to the swappiness step, or remove the old one first with the last step of this tutorial.
Step 2 · Create the swap file, private from the first byte
Anyone who can read a swap file can read whatever memory was paged into it: session tokens, database rows, passwords typed into a running program. So create the file as root-only first, then give it its size, rather than fixing the permissions afterwards.
sudo install -m 600 /dev/null /swapfile
sudo fallocate -l 2G /swapfile
ls -l /swapfileinstall -m 600 /dev/null /swapfile creates an empty file owned by root with mode 600 (read and write for root, nothing for anyone else). fallocate then reserves 2 GB of real disk blocks without writing them, which takes under a second. Both keep the mode you set.
The kernel needs every block of a swap file to exist on disk. On ext4, the default on Ubuntu, fallocate gives it that. On some other filesystems the kernel treats a preallocated file as having holes. swapon in the next step then fails with swapon: /swapfile: swapon failed: Invalid argument, and sudo dmesg | tail shows swapon: swapfile has holes. If that happens, write the file out in full with dd instead. It replaces the contents and keeps the 600 mode:
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progressThat writes 2048 blocks of 1 MiB, so it takes as long as your disk needs to write 2 GB. On Btrfs neither command is enough, because copy-on-write files cannot be used as swap; remove the file you just made with sudo rm /swapfile, then run sudo btrfs filesystem mkswapfile --size 2G /swapfile. It refuses a path that already exists, and it creates the file itself with mode 600, copy-on-write turned off and the swap signature already written. Check which filesystem holds / with findmnt -no FSTYPE /.
Check it worked
ls -l /swapfile shows -rw-------, owner root root, and a size of 2147483648 bytes. Any r in the last six characters means other users can read the file; delete it and start again with install -m 600.
Step 3 · Format it as swap and turn it on
mkswap writes a small header that marks the file as swap space and gives it a UUID:
sudo mkswap /swapfile
sudo blkid /swapfilemkswap prints something like Setting up swapspace version 1, size = 2 GiB (2147479552 bytes) followed by no label, UUID=.... blkid reads the header back and reports the type.
Now give the swap space to the kernel:
sudo swapon /swapfile
swapon --show
free -hCheck it worked
blkid prints a line ending in TYPE="swap". After swapon, swapon --show lists /swapfile with type file, size 2G and USED at or near 0B, and the Swap: line in free -h shows a total of about 2.0Gi. If swapon fails with Invalid argument and sudo dmesg | tail mentions swapfile has holes, go back to the dd command in the previous step and run mkswap again.
Step 4 · Turn the swap file on at every boot
swapon lasts until the next reboot. To make it permanent, add a line to /etc/fstab. A broken /etc/fstab can stop the server from booting normally, so keep a copy of the current file first:
sudo cp /etc/fstab /etc/fstab.bak
grep -q '^/swapfile ' /etc/fstab || echo '/swapfile none swap defaults 0 0' | sudo tee -a /etc/fstabThe grep -q ... || part only appends the line if there is no /swapfile line yet, so running the command twice does not add a duplicate. The six fields are the file, the mount point (none, because swap is not mounted anywhere), the type swap, the options, and two zeros that turn off dump backups and boot-time fsck. /tutorials/mount-a-disk-at-boot-with-fstab-and-uuids explains every field in more depth.
Ask findmnt to check the whole file before you trust it to a reboot:
sudo findmnt --verify --verboseThen prove the line works without rebooting: turn the swap off and let swapon read /etc/fstab the way the boot process does.
sudo swapoff /swapfile
sudo swapon --all --verboseCheck it worked
findmnt --verify ends with Success, no errors or warnings detected (or a count such as 0 parse errors, 0 errors, 1 warning if something needs attention), and its verbose output for /swapfile says the source exists and the type is swap. swapon --all --verbose prints swapon: /swapfile: found signature [pagesize=4096, signature=swap] and swapon /swapfile, and swapon --show lists the file again. If findmnt reports an error, fix or remove the line now: sudo cp /etc/fstab.bak /etc/fstab puts the old file back.
Step 5 · Tell the kernel how eagerly to swap
vm.swappiness sets how willing the kernel is to move process memory to swap rather than drop file cache. It ranges from 0 to 200 and defaults to 60. For a server where swap is a safety net, a lower value such as 10 keeps your app's memory in RAM until RAM is really short.
See the current value:
sysctl vm.swappinessWrite the setting to a drop-in file of its own, so it is easy to find and remove, and survives package upgrades that change other sysctl files:
echo 'vm.swappiness = 10' | sudo tee /etc/sysctl.d/90-swappiness.confFiles in /etc/sysctl.d/ are applied at boot in name order, so a file starting with 90- wins over the lower-numbered files that packages install. Apply it now:
sudo sysctl -p /etc/sysctl.d/90-swappiness.conf
sysctl vm.swappiness/tutorials/tune-kernel-parameters-with-sysctl covers how sysctl drop-ins override each other and how to find which file set a value.
Check it worked
Before applying, sysctl vm.swappiness prints vm.swappiness = 60 on a stock server. After sudo sysctl -p, it prints vm.swappiness = 10, and cat /etc/sysctl.d/90-swappiness.conf shows the one line you wrote. Over the next days, free -h should show Swap: used staying small during normal load and rising only at peaks. If it climbs and stays high, the server needs more RAM, not more swap.
Step 6 · Consider zram instead of a swap file
zram is swap held in RAM, compressed. Pages that would go to disk are squeezed (often to a third of their size) into a block device in memory instead. It is much faster than disk swap and does not wear out SSDs, but it uses some CPU and some of the RAM it is trying to save. It suits servers with slow or metered disks, and small ARM boards. Ubuntu packages the systemd generator that sets it up:
sudo apt install systemd-zram-generatorConfigure one zram device of half the RAM, capped at 2 GB, compressed with zstd:
sudo tee /etc/systemd/zram-generator.conf > /dev/null <<'EOF'
[zram0]
zram-size = min(ram / 2, 2048)
compression-algorithm = zstd
EOF
sudo systemctl daemon-reload
sudo systemctl start systemd-zram-setup@zram0.servicezram swap gets priority 100 by default, higher than a swap file's, so if you keep both, the kernel fills zram first and only spills to the file when zram is full. That combination works well on a 1 GB server.
Check it worked
zramctl lists /dev/zram0 with algorithm zstd and a DISKSIZE of about half your RAM, and swapon --show lists /dev/zram0 with type partition and priority 100. The device comes back by itself after a reboot, because the generator reads the config file at every boot.
Step 7 · Remove the swap file cleanly
You might remove swap after moving to a bigger plan, or to replace the file with zram. Turn the swap off first. swapoff moves every page in the file back into RAM, so run it when free -h shows enough available memory to hold what Swap: used reports; otherwise the out-of-memory killer can fire while it works.
sudo swapoff /swapfileBefore deleting anything, confirm the kernel no longer uses the file:
if swapon --show=NAME --noheadings | grep -qx /swapfile; then echo "/swapfile is still in use: run sudo swapoff /swapfile first"; false; fiThen remove the fstab line, the file, the sysctl drop-in and the fstab backup:
sudo sed -i '\|^/swapfile |d' /etc/fstab
sudo rm /swapfile /etc/sysctl.d/90-swappiness.conf /etc/fstab.bakThe removed drop-in stops applying at the next boot. To go back to the default straight away, run sudo sysctl -w vm.swappiness=60.
Check it worked
grep swapfile /etc/fstab prints nothing, ls /swapfile reports No such file or directory, and swapon --show no longer lists /swapfile. sudo findmnt --verify still reports no errors. df -h / shows about 2 GB more free space than before.
Next steps
- Find out which process is using the memory before you add more swap, with
/tutorials/find-what-is-using-memory-and-read-oom-killer-messages. - Learn how other kernel settings are layered and applied in
/tutorials/tune-kernel-parameters-with-sysctl. - Mount a data disk by UUID and test its fstab line safely with
/tutorials/mount-a-disk-at-boot-with-fstab-and-uuids.
Related tutorials
- Write safer Bash scripts with strict mode and trapsYou will build a small Bash release script that stops on the first error, says which line failed, survives file names with spaces and always removes its temporary files.
- Write least-privilege sudo rules with visudoYou will replace blanket sudo access with checked rule files in /etc/sudoers.d that let two operators restart one service and edit one file, give an automation account a password-free command list, and audit what every account can run.
- Upgrade a server from Ubuntu 24.04 LTS to 26.04 LTSYou will take a backed-up Ubuntu 24.04 server through do-release-upgrade to 26.04 LTS over SSH with a fallback login, then confirm services, repositories and language runtimes work on the new release.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials