Create a Swap File (fallocate + mkswap + swapon)

Add swap space without repartitioning by creating a /swapfile, formatting it with mkswap and enabling it with swapon.

LinuxswapfilesystemmemorystorageMedium risk
Run `sudo fallocate -l 4G /swapfile && sudo chmod 600 /swapfile && sudo mkswap /swapfile && sudo swapon /swapfile` to add 4 GB of swap.

01Command

Command
$ sudo fallocate -l 4G /swapfile && sudo chmod 600 /swapfile && sudo mkswap /swapfile && sudo swapon /swapfile

02What it does

Swap lets the kernel page out cold memory, which saves a small server from OOM-kills when traffic spikes; 2–4 GB is a common size for a VPS with 1–2 GB RAM. The chmod 600 step matters — swap files must not be world-readable or swapon warns. To keep it after a reboot, append `/swapfile none swap defaults 0 0` to /etc/fstab, and tune swappiness with `sysctl vm.swappiness=10` for desktops.

03Risk

RiskMedium risk
RequirementsRoot privileges and free disk space. To persist across reboots, add `/swapfile none swap defaults 0 0` to /etc/fstab. Verify with `swapon --show` and `free -h`.
!Warning: Never do this while /swapfile already exists with data — fallocate will reuse the file and mkswap overwrites it. Some filesystems (btrfs, ZFS) need special handling (swaplimits/NOCOW) before a swap file is safe.

04Undo

Undo
$ sudo swapoff /swapfile && sudo rm /swapfile

05Sources

  • Swap - ArchWiki
    Arch Linux Wiki · technical · 2026-09-17
    Evidence: Documents creating a swap file with fallocate, setting permissions with chmod 600, mkswap, swapon and the /etc/fstab entry to make it permanent.
  • swapon(8) - Linux manual page
    Ubuntu Manpages · technical · 2026-09-17
    Evidence: swapon enables a swap device or file and swapon --show reports active swap areas.

Last verified: 2026-09-18 · Category: System & Settings

06Related solutions