How to add swap and size it

Topic: Servers linux

Summary

Create a swap file or partition, enable it with swapon, and add it to fstab so it survives reboot. Size swap based on workload: often equal to RAM for small servers, or less when you have plenty of RAM. Use this when you see OOM or need to reduce memory pressure.

Intent: How-to

Quick answer

  • Create swap file: fallocate -l 2G /swapfile (or dd); chmod 600 /swapfile; mkswap /swapfile; swapon /swapfile. Add to /etc/fstab: /swapfile none swap sw 0 0.
  • Size: 1x–2x RAM for low-RAM systems; smaller or none for large RAM. Set vm.swappiness (e.g. 10) to reduce swapping if you prefer keeping more in RAM.
  • Verify with free -h and swapon --show; ensure swap is in fstab so it activates on boot; do not put swap on SSDs without considering wear if heavy swap use.

Prerequisites

Steps

  1. Create swap file

    sudo fallocate -l 2G /swapfile (or dd if fallocate fails); sudo chmod 600 /swapfile; sudo mkswap /swapfile; sudo swapon /swapfile. Use a path on a disk with enough free space (e.g. / or dedicated volume).

  2. Make persistent

    Add line to /etc/fstab: /swapfile none swap sw 0 0. Run sudo swapon -a to test fstab; reboot to confirm swap is active after boot.

  3. Tune swappiness (optional)

    sysctl vm.swappiness=10 to prefer RAM over swap; add vm.swappiness=10 to /etc/sysctl.d/99-swap.conf to persist. Lower values reduce swap use when RAM is available.

Summary

Add a swap file (or partition), enable it with swapon, and add it to fstab. Size it for your workload; tune swappiness if you want to limit swapping. Use this to avoid OOM or to absorb memory spikes.

Prerequisites

Steps

Step 1: Create swap file

sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

Step 2: Make persistent

Add to /etc/fstab:

/swapfile none swap sw 0 0

Run sudo swapon -a and reboot to confirm.

Step 3: Tune swappiness (optional)

sudo sysctl vm.swappiness=10

Persist in /etc/sysctl.d/ if desired.

Verification

  • free -h and swapon --show show the new swap; after reboot swap is still active.

Troubleshooting

fallocate fails — Use dd if=/dev/zero of=/swapfile bs=1M count=2048 instead. Swap not on boot — Check fstab path and options; run swapon -a and check dmesg. Heavy swap on SSD — Consider sizing down or moving swap to HDD to reduce wear.

Next steps

Continue to