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.
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 /swapfile02What 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
!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 /swapfile05Sources
- Swap - ArchWikiEvidence: 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 pageEvidence: swapon enables a swap device or file and swapon --show reports active swap areas.
Last verified: 2026-09-18 · Category: System & Settings