
Swap often decides whether you get a brief hiccup or a real outage. On a small VPS, a PHP worker burst, a WordPress import, or a compression job can peg RAM at 100% and trigger the Linux OOM killer.
This VPS swap configuration tutorial shows how to add swap safely on Ubuntu and Debian, tune it for hosting workloads, and confirm you didn’t trade crashes for sluggish performance.
If you’re running production sites, schedule this in a low-traffic window. Change one thing at a time. Keep rollback steps nearby.
VPS swap configuration tutorial: choose the right swap approach for your server
For most VPS hosting setups, a swap file is the best default. It’s fast to create, easy to resize, and simple to remove.
A swap partition can be slightly faster in some cases. Resizing later is usually a hassle.
- Swap file (recommended): easy to create, resize, and remove.
- Swap partition: useful only if your image already includes one (less common on VPS templates).
- zram: compressed RAM swap; helpful on ultra-small instances, but it adds CPU overhead and makes tuning less straightforward.
Keep expectations realistic. Swap won’t “speed up” your server.
Swap buys stability during short memory spikes. If the box lives in swap, you need more RAM or fewer concurrent workers.
If you hit limits regularly, upgrading to a larger HostMyCode VPS is usually the cleanest fix. Treat swap as a safety net, not a permanent coping strategy.
Pre-flight checks (2 minutes): verify memory pressure and disk headroom
Before you create swap, verify two things. Confirm you’re under memory pressure. Then confirm you have enough disk space.
Swap lives on disk. A packed root filesystem can cause a different kind of outage.
# RAM and current swap
free -h
# Top memory consumers (interactive)
top
# Disk space (swap file will be stored on / by default)
df -h /
Quick interpretation:
- If
Swap: 0B, you have no swap configured right now. - If
/has less than ~3–5 GB free, don’t drop a large swap file there. Clean up first or attach/mount more storage.
If disk pressure is already an issue, fix that first.
These guides pair well with this workflow: VPS disk space troubleshooting and logrotate setup for hosting logs.
Create a swap file on Ubuntu/Debian (safe, repeatable steps)
The steps below work on Ubuntu Server (including 24.04/26.04 images commonly used in 2026) and Debian 12/13. Run them as root or with sudo.
Step 1: decide swap size (practical hosting guidance)
- 1 GB RAM VPS: 1–2 GB swap (within your disk comfort zone).
- 2 GB RAM VPS: 2 GB swap is usually enough.
- 4–8 GB RAM: 2–4 GB swap for burst protection.
- 16 GB+: swap still helps with rare spikes; 4–8 GB is fine.
On database servers (MySQL/MariaDB), swap is a guard rail, not a performance feature.
If swap gets used often, expect query latency to climb. Plan to watch it after rollout.
Step 2: create the swap file
Use fallocate where it’s supported because it’s fast. If your filesystem makes fallocate unreliable or sparse, use dd instead.
# Example: create a 2G swap file
sudo fallocate -l 2G /swapfile
# If fallocate fails or creates a sparse file, use dd instead:
# sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress
Step 3: lock down permissions (important)
sudo chmod 600 /swapfile
sudo ls -lh /swapfile
You want permissions to read as -rw-------. Anything more permissive is an avoidable security risk.
Step 4: format and enable swap
sudo mkswap /swapfile
sudo swapon /swapfile
# Verify
swapon --show
free -h
If swapon --show lists /swapfile, swap is live.
Step 5: make it persistent across reboots
Add an entry to /etc/fstab. For a swap file, the line stays simple:
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
# Sanity check the file
tail -n 5 /etc/fstab
Rollback tip: Disable swap quickly with sudo swapoff /swapfile. Then remove the line from /etc/fstab.
Tune swap for hosting workloads: swappiness and cache pressure
Linux defaults are often fine. Many hosting stacks behave better with a less aggressive swap policy.
You want PHP-FPM, Redis, and database pages to stay in RAM. Only spill to swap when memory is genuinely tight.
Set a sensible swappiness
vm.swappiness controls how readily the kernel swaps. For many web hosting workloads, 10 is a solid starting point.
# Check current value
sysctl vm.swappiness
# Set temporarily (until reboot)
sudo sysctl vm.swappiness=10
Persist it in /etc/sysctl.d/99-swap-tuning.conf:
cat <<'EOF' | sudo tee /etc/sysctl.d/99-swap-tuning.conf
vm.swappiness=10
EOF
sudo sysctl --system
Optional: tune vfs_cache_pressure
This controls how aggressively the kernel reclaims inode/dentry caches.
If you serve lots of small files (WordPress themes/plugins, thumbnails, cached assets), lowering it can keep filesystem metadata warm.
# Common starting point for web servers
sudo sysctl vm.vfs_cache_pressure=50
cat <<'EOF' | sudo tee -a /etc/sysctl.d/99-swap-tuning.conf
vm.vfs_cache_pressure=50
EOF
sudo sysctl --system
If memory use rises without a clear benefit, go back to the default (100).
Add a safety net: enable early OOM protection (systemd-oomd)
Swap helps, but you also want predictable behavior during extreme pressure.
On systemd-based distros, systemd-oomd can end the right processes earlier. That’s often better than letting the host grind through swap thrash until the site falls over.
# Check if systemd-oomd exists and is enabled
systemctl status systemd-oomd --no-pager
If it’s installed but disabled:
sudo systemctl enable --now systemd-oomd
On the first pass, avoid heavy oomd tuning. Get swap stable first and watch behavior for a week.
Busy stacks (control panels, mail, multiple PHP versions) can react in surprising ways to aggressive OOM rules.
Verify swap is actually working (and not silently hurting performance)
After you enable swap, don’t assume it’s fine.
Confirm swap exists, your kernel tunables applied, and the server isn’t swapping during normal traffic.
Confirm swap and kernel tunables
swapon --show
sysctl vm.swappiness vm.vfs_cache_pressure
Watch swapping in real time
# Install if needed
sudo apt-get update && sudo apt-get install -y sysstat
# Real-time swap-in/swap-out every 1s
vmstat 1
Pay attention to:
si(swap in) andso(swap out): near 0 during normal load is what you want.wa(I/O wait): if it climbs whilesi/sorise, you’re likely thrashing.
Check memory pressure metrics (modern kernel view)
# PSI: pressure stall information
cat /proc/pressure/memory
cat /proc/pressure/io
If some avg10 or full avg10 stays consistently high, the box is starved.
Swap may keep it alive, but users will feel the latency.
Common hosting scenarios and the swap settings that usually work
WordPress on Nginx/Apache + PHP-FPM
Expect spikes during plugin updates, bulk imports, and bot storms.
Swap helps prevent the OOM killer from taking out php-fpm or your database during a burst.
- Swap size: 2–4 GB (depending on RAM)
- Swappiness: 10
- Also do: rate limiting and WAF rules to keep junk traffic from creating worker storms
If brute-force traffic is driving memory up, pair this with Nginx rate limiting or a WAF rollout.
cPanel/WHM hosting VPS (multi-account)
Control panel services plus multiple PHP pools add up fast.
Swap reduces the odds that one runaway account takes the whole server down. You still need isolation and hard limits.
- Swap size: 4 GB minimum on serious reseller nodes
- Swappiness: 10 (sometimes 5 if you have plenty of RAM)
- Also do: account isolation and PHP-FPM tuning per domain
For the wider hardening baseline, start here: cPanel hardening tutorial.
Resizing swap safely (and how not to brick the box)
You’ll eventually guess wrong on swap size. Resizing a swap file is safe if you follow this order: off, resize, reformat, on.
Increase swap file size
Example: grow from 2 GB to 4 GB.
sudo swapoff /swapfile
sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
swapon --show
Reduce swap size
Reducing uses the same workflow: disable, recreate smaller, re-enable.
Don’t try to shrink a swap file in place.
Pitfall: if the server is actively swapping, swapoff can hang. The kernel needs RAM to page everything back in.
Stop memory-heavy services first (PHP workers, background jobs), or schedule a controlled reboot during a quiet period.
Troubleshooting: swap is enabled, but the server is still slow
Swap avoids crashes, but disk-backed memory is slow.
If latency jumps after adding swap, you’ve likely exposed a RAM sizing issue or a workload spike.
Diagnosis checklist
- Is swap constantly used? Check
free -handvmstat 1. Continuoussi/soactivity points to thrash. - Is I/O the bottleneck? Use
iostat -xz 1(fromsysstat). High await/util during swap activity is a warning sign. - Which process is growing? Use
ps aux --sort=-%mem | headand check logs. - Are bots causing worker explosions? Correlate access logs with 5xx spikes.
# Top memory users
ps aux --sort=-%mem | head -n 15
# Quick view of memory maps for a PID (replace 1234)
cat /proc/1234/status | egrep 'VmRSS|VmSwap|Name'
If your logs show traffic bursts lining up with swap churn, investigate directly with VPS log analysis. It beats guessing.
Swap won’t turn on (common errors)
- “Operation not permitted”: your filesystem or mount options may block swap files. Try a different filesystem or use a partition.
- Swap file is sparse: some environments create sparse files with
fallocate. Recreate withddand re-runmkswap. - “Text file busy” / in use: confirm it’s disabled with
swapoff /swapfilebefore reformatting.
Operational best practices: keep swap from hiding real capacity issues
Swap should reduce incidents, not make them harder to diagnose. Two habits make a noticeable difference:
- Alert on swap usage. If swap sits above ~10–20% for any length of time, treat it as a scaling signal.
- Run a restore/maintenance drill. Memory incidents often appear during upgrades and migrations. Practice the workflow before you need it.
For monitoring, you can wire alerts quickly with Uptime Kuma + Node Exporter monitoring and add a swap usage threshold.
If you’re running WordPress, mail, or multiple client sites, swap is only one piece of uptime. The bigger wins come from a correctly sized VPS, fast storage, and sane service limits. Use managed VPS hosting if you want HostMyCode to handle OS-level tuning and ongoing checks, or start with a flexible HostMyCode VPS and use this guide as your baseline.
FAQ: swap on a hosting VPS
How much swap should I add for WordPress on a 2 GB VPS?
Start with 2 GB. That usually covers short spikes from PHP-FPM bursts, imports, and updates.
If swap stays busy, add RAM instead of piling on more swap.
Will swap damage SSD/NVMe on my VPS?
Occasional swap use is fine. Constant swapping is the real problem because it drives sustained writes and increases I/O wait.
If you see ongoing swap churn, reduce concurrency, fix runaway processes, or upgrade the plan.
Why did my server get slower after adding swap?
Because the kernel now has a “slow memory” option instead of killing a process. That’s good for uptime, but it exposes undersized RAM or a sudden workload spike.
Use vmstat and logs to find what changed.
Should I set swappiness to 1?
Usually not. A value that low can discourage swap even when it would prevent an OOM event.
For most hosting workloads, 10 is a better balance.
Is zram better than a swap file?
zram can help on tiny servers because it swaps into compressed RAM, but it costs CPU and adds tuning complexity.
For most hosting VPS setups, a swap file plus monitoring is simpler and more predictable.
Summary: a stable swap setup you can keep
You now have persistent swap, conservative swap behavior, and a way to measure real impact. Watch swap activity for a week.
If it stays near zero, you gained crash protection with little downside. If it climbs and stays high, treat it as a capacity warning.
If you want a cleaner baseline for production hosting in 2026—right-sized resources, fast storage, and optional hands-on help—start with a HostMyCode VPS or move to managed VPS hosting to offload the routine tuning and checks.