brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: mkswap and swapon add a swap file without repartitioning

Linux
~/tips/tip-disk-swapfile-mkswap-swapon

sudo mkswap /swapfile

Gives a Linux machine swap space from a plain file, without changing any partitions.

A small VPS or a VM with too little memory and no swap partition: you don’t need to touch the partition table to give it swap. A plain file works too, and it takes four commands. There’s one trap in how you create that file, which is why I’d follow the man page here instead of a random snippet.

sudo dd if=/dev/zero of=/swapfile bs=1MiB count=4096
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
swapon --show

That makes a 4 GiB file, turns it into swap and switches it on. swapon --show prints a table of the active swap areas with their size and how much is used, and the man page prefers it over the older swapon -s. The chmod 600 keeps other users from reading the file, because it will hold pieces of memory.

To have it back after a reboot, add a line to /etc/fstab. swapon wants an absolute path for a file, none as the mount point by convention, and swap as the type:

/swapfile  none  swap  defaults  0  0

Newer versions of util-linux have a shortcut: sudo mkswap --file --size 4G /swapfile creates the file with the right permissions and blocks in one go.

About that trap: the kernel writes to a swap file directly, without help from the filesystem, so the file can’t have holes. The swapon man page says files made by cp or truncate get rejected, and a file from fallocate may count as having holes too, depending on the filesystem. The man page calls dd from /dev/zero the most portable way, which is why I used it above. On Btrfs a swap file also needs the nocow attribute (supported since Linux 5.0), and since util-linux 2.41 mkswap --file sets that for you. And skip swap on an NFS mount: the man page says it may not work.

Further reading: mkswap(8) manual page, swapon(8) manual page

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link