Create a Swap File on Linux

A swap file lets the kernel move idle pages out of RAM onto disk. It’s handy on small-memory hosts (VPS, VMs) that have no dedicated swap partition, and unlike a partition it can be resized or removed without repartitioning. Create the swap file 1 2 3 4 5 6 7 # Allocate a 1 GiB file. dd is preferred over fallocate here because # swapon rejects files with holes on some filesystems (e.g. ext4, XFS). dd if=/dev/zero of=/swapfile bs=1M count=1024 status=progress chmod 0600 /swapfile # only root may read/write the swap file mkswap /swapfile # format it as swap space swapon /swapfile # enable it immediately Make it persistent Add an entry to /etc/fstab so the swap file is mounted on every boot. The grep guard keeps this idempotent — running it twice won’t add a duplicate line. ...

August 11, 2022 · 2 min · 227 words · Terence