CH-J Toolsserver management over SSH
Menu
All guides and articles →

How to create or grow swap on Ubuntu and Debian

Check memory use, create a swap file, make it persistent and resize it safely, with notes on Btrfs and zram.

What problem does a swap file solve?

A package upgrade starts while a database and application workers already use most of a small server's RAM. The machine becomes slow, or a process disappears under memory pressure. A swap file provides disk space where Linux can keep less active memory pages, leaving RAM for work that needs it now. It can absorb a temporary peak, but disk access is much slower than RAM access.

This guide covers Ubuntu and Debian servers with sudo access. The ordinary file examples assume a local ext4 filesystem; verify that before using them. Btrfs has a separate procedure below. If you administer the server from Windows, run the commands in its Linux SSH session, not in local PowerShell. A Windows page file is a different mechanism.

Creating swap means activating it now and configuring activation after boot. Check both separately. A file existing on disk does not mean Linux uses it, and successful activation today does not prove it will return after restart.

Why can memory look full without a problem?

Linux uses otherwise idle RAM for caches. A small free value alone is therefore a poor reason to add swap. Available memory is a better starting point: it estimates room for applications after reclaiming usable cache. Read it together with workload behaviour rather than treating a single percentage as a diagnosis.

  • Short peaks can come from backups, builds, upgrades or scheduled jobs running together.
  • Persistent pressure can come from too many workers, an oversized application cache or a memory leak. More swap buys time but does not remove the cause.
  • A container can hit its own memory limit while the host still has spare RAM. Swap administration may require access to the host.

There is no universal rule that swap must be twice RAM. Choose capacity from observed peaks, acceptable response times and disk space. The 2 GiB example below is an example size, not a recommendation for every database or virtual machine.

What should you check before changing anything?

Collect a baseline during the usual workload. These commands inspect memory, active swap, activity, storage and existing boot configuration. The final check reveals an existing file or symbolic link at the proposed path. A missing /swapfile is expected when creating it for the first time.

free -h
swapon --show
vmstat 1 5
df -h /
findmnt -no TARGET,SOURCE,FSTYPE -T /
grep -nE "^[[:space:]]*[^#].*[[:space:]]swap[[:space:]]" /etc/fstab
sudo ls -ld /swapfile

In vmstat, si and so describe swapping in and out. The first activity report covers time since boot; subsequent reports cover the sampling interval. Repeated activity alongside poor response times deserves investigation. Nonzero used swap may simply contain pages left from an earlier peak, with little current activity.

Leave disk space for logs, updates and application growth after allocating swap. If /swapfile already exists, stop and identify it; do not overwrite it. Record existing swap partitions and zram devices too, so you know which capacity belongs to which path.

How do you create a new ext4 swap file?

Continue only after confirming ext4, enough disk space and an unused /swapfile path. Writing 2048 blocks of 1 MiB gives a 2 GiB file without holes. The exclusive creation flag refuses an existing destination. The root shell sets restrictive permissions from creation.

mkswap writes a swap header and damages existing contents. Use it only on the new file you created and checked. Swap can contain passwords and other sensitive memory; keep the file owned by root and inaccessible to other users.

  1. Create the file and wait for completion. Stop on any error.
  2. Check root ownership, mode 600 and size 2147483648 bytes.
  3. Initialize the checked file, then activate it. Run each command only after the previous step succeeds.
  4. Confirm the exact path in the active swap list before changing boot configuration.
sudo sh -c 'umask 077; dd if=/dev/zero of=/swapfile bs=1M count=2048 conv=excl status=progress'
sudo stat -c '%U %a %s %n' /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
swapon --show

A failed write can leave a partial file. Do not format it or blindly rerun creation. Inspect the error, disk space and exact destination first. Leave fstab unchanged until creation and activation succeed.

How do you enable swap after a restart?

Back up /etc/fstab before editing. The numbered backup command preserves an existing backup instead of silently replacing it. Inspect existing swap lines and use sudoedit to add exactly one entry for the file.

Incorrect changes to /etc/fstab can disrupt boot or leave filesystems unavailable. Keep the backup and console access available, and resolve verification errors before restarting.

sudo cp --backup=numbered --preserve=mode,ownership,timestamps /etc/fstab /etc/fstab.backup
sudoedit /etc/fstab

Add this configuration line in the editor, not in the shell. The path identifies the file, none indicates no ordinary mount point, and the zero fields disable dump and filesystem checks for this entry.

/swapfile none swap sw 0 0

On a systemd-based Ubuntu or Debian installation, verify fstab and reload generated unit configuration. Correct any verification errors first. swapon -a processes all enabled fstab swap entries and skips active areas, so review the other entries before running it.

sudo findmnt --verify
sudo systemctl daemon-reload
sudo swapon -a
swapon --show

How do you verify that the change helped?

Check that the path appears in swapon output, total swap capacity has increased and applications remain responsive. A new file may show zero usage when Linux has no reason to move pages into it. Do not create artificial memory pressure on a production server to force a demonstration.

swapon --show
free -h
vmstat 1 5

Repeat observations during the workload that previously caused trouble and after the next planned reboot. Verification while an active file is skipped cannot prove successful boot activation. If swap disappears after reboot, inspect its fstab path and boot journal. For activation failures, read kernel messages; repeating mkswap does not fix every Invalid argument error.

sudo journalctl -k -b -n 50 --no-pager

How do you grow or shrink swap safely?

Adding another file is the simplest way to grow capacity. To replace 2 GiB with 4 GiB, prepare /swapfile-extra while the original stays active. On ext4, repeat the creation checks for that unused path and allow another 4 GiB plus working disk space. Stop at any error. Before mkswap, confirm root ownership, mode 600 and 4294967296 bytes.

sudo ls -ld /swapfile-extra
df -h /
sudo sh -c 'umask 077; dd if=/dev/zero of=/swapfile-extra bs=1M count=4096 conv=excl status=progress'
sudo stat -c '%U %a %s %n' /swapfile-extra
sudo mkswap /swapfile-extra
sudo swapon /swapfile-extra
swapon --show

For extra capacity, keep both files and persist the new path using the backup and validation procedure above. For replacement, persist the new path first, reduce workload, then check memory before deactivating only the old file.

swapoff must bring pages back into memory and can fail under pressure; workloads may suffer or processes may be killed. Require available RAM comfortably above the old area's used swap, with margin for changing demand. Postpone if uncertain. An extra swap file alone is not a guarantee.

free -h
swapon --show
sudo swapoff /swapfile
swapon --show

Run swapoff only after evaluating those checks. If it fails, keep the old file and entry. After success, confirm /swapfile is absent from the active list, back up fstab again and remove only its old entry. Keep the inactive file until the replacement is verified; delete it only after checking its exact path and inactive status again. Shrinking uses the same approach with a smaller replacement and careful review of remaining capacity. Never truncate, overwrite or resize an active file.

What changes with Btrfs, zram and zswap?

Do not use the ext4 recipe on Btrfs. With btrfs-progs 6.1 or later, this helper prepares the file with required attributes. The example assumes / is Btrfs and /swap does not exist. Check disk space first. A dedicated subvolume keeps swap outside snapshots: a subvolume containing active swap cannot be snapshotted. Suitable extent placement is required, without holes, compression or copy-on-write; not every storage layout qualifies.

btrfs --version
findmnt -no TARGET,SOURCE,FSTYPE -T /
sudo ls -ld /swap
sudo btrfs subvolume create /swap
sudo btrfs filesystem mkswapfile --size 2G /swap/swapfile
sudo swapon /swap/swapfile

Stop on errors or an existing destination. With older tooling, follow the distribution's documented procedure. Persist /swap/swapfile only after successful activation, using the fstab checks above.

zram stores compressed pages in RAM and can provide a swap device. Identify its managing service or generator before changing configuration; a disk file does not resize zram. zswap is a compressed RAM cache in front of backing swap, not a separate swap file. Do not apply file creation or deletion commands to either mechanism.

Which habits prevent future swap problems?

  • Monitor available RAM, swap activity and application response during normal peaks. Sustained paging calls for workload changes or more RAM.
  • Keep disk headroom and document paths, sizes and fstab entries. Avoid swapoff -a when replacing only one file.
  • Do not create sparse swap files with truncate or assume an ordinary copied file has a suitable layout. Follow the filesystem-specific procedure.
  • Keep permissions restrictive. Consider encryption of the storage containing swap for sensitive systems; permissions do not protect an offline disk.

Avoid changing swappiness just to make a graph look cleaner. Establish a baseline and assess the workload before tuning. Hibernation needs separate planning: recreating a file can change resume information. This server procedure configures ordinary swapping, not hibernation recovery.

How does CH-J Tools help with swap?

System Monitor in CH-J Tools shows a RAM breakdown, RAM and swap history, and each swap area with its type, priority and activity.

  • With root or sudo, you can create, activate, deactivate, resize and delete swap files in /swapfile*, /swap/<name> or /var/lib/swap/<name>.
  • Supported sizes are 64 MiB to 64 GiB on ext2/3/4, XFS, Btrfs and F2FS.
  • The application refuses to deactivate swap whose contents would not fit into memory and backs up /etc/fstab before each change.
  • zram and zswap are read-only in the application.

Frequently asked questions

Does used swap mean the server is running out of RAM?

Not necessarily. Inactive pages can remain after a short peak. Look at available RAM, current swap activity and response times together. Used capacity alone does not establish ongoing pressure.

Can I add swap without rebooting?

Yes. Activate the initialized file on the running system. Its fstab entry provides persistence; verify that separately and check the result after a planned restart.

Why does swapon report Operation not permitted with sudo?

A restricted container may deny swap administration even to container root. Ask the host administrator to check its policy. Repeated formatting will not grant missing permission.

Can swap prevent every out-of-memory kill?

No. Demand can exceed RAM and swap together, and service or container limits may apply separately. Swap cannot make an undersized machine deliver RAM-like performance during sustained paging.

Must I keep the same file name when replacing swap?

No. Use the new absolute path consistently in activation commands and fstab. Remove the old entry after successful deactivation. Use the file path here rather than relying on the UUID printed by mkswap.

Detailed documentation

man: swapon →

man: mkswap →

man: fstab →

man: free →

man: vmstat →

Linux kernel: zram →

Linux kernel: zswap →

Biometric unlock and security →

All tutorials by category →