Linux swap file setup for a low-RAM VPS
Linux swap file setup for a low-RAM VPS, with practical sizing rules, OOM tradeoffs, checks, and when to upgrade RAM instead.
Dedicated servers and small-business DevOps
He compares dedicated servers, unmanaged VPS plans, support promises, and the real cost of keeping a stack online.
When RAM runs out, a swap file gives a Linux VPS breathing room, not free speed. Use it for short spikes, updates, and background jobs; upgrade RAM when swap stays busy, because disk-backed memory turns slow before it saves you.
What a swap file actually changes
Linux uses swap as overflow memory. When physical RAM gets tight, inactive pages can move to disk so the processes doing real work keep running. That can prevent an abrupt out-of-memory kill during a package update, a deploy, or a one-off traffic spike.
The tradeoff is plain: storage is much slower than RAM. On an NVMe VPS, swap hurts less than it would on old network storage, but it still turns memory pressure into latency. It should buy recovery time, not become the normal shape of the server.
This matters on small VPS plans from Hostinger, Hetzner, or IONOS because the cheapest virtual servers often leave little slack after the OS, database, web server, and monitoring agent are running.
When swap helps, and when it lies
Swap helps when the memory spike is brief and predictable. Good examples are unattended upgrades, image processing jobs, log rotation, build steps, and a database restart that temporarily holds more memory than usual.
Swap lies when it hides a steady leak or a workload that has outgrown the plan. If swap activity stays high during ordinary traffic, the server is not stable. It is waiting for the after-hours failure: a disk stall, a queue buildup, or another OOM event.
| Situation | Swap is useful when | Treat it as a warning when |
|---|---|---|
| Package updates | The spike ends after the update finishes. | The system becomes sluggish after every routine update. |
| Small databases | Cache pressure appears during maintenance. | Queries keep touching swap during normal reads. |
| Web traffic | A short burst clears without manual rescue. | Workers pile up and response time climbs. |
| Background jobs | A scheduled job occasionally needs more headroom. | Jobs overlap and swap stays active between runs. |
The practical goal is survivability, not speed. A server that occasionally writes cold pages to swap can be fine. A server that constantly reads hot pages from swap needs less workload, tighter limits, or more RAM.
Before you add swap
Check whether your provider and plan make swap a sensible stopgap. A VPS with local NVMe storage is a better candidate than a plan where disk I/O is already the bottleneck. Also check whether backups, snapshots, or full-disk images include the swap file.
Look at memory pressure before changing the server. The useful signals are free memory, existing swap use, OOM messages, and whether the busiest process is expected. Do this during the problem window, not hours later when the server looks innocent.
Check these signals before the change:
- Available memory should show whether the server is briefly tight or already undersized.
- Existing swap should be empty or explainable before you add another layer.
- OOM logs should name the process that pushed the server over the edge.
free -h
swapon --show
dmesg -T | grep -i "out of memory\\|oom"
ps aux --sort=-%mem | head
If the largest process is a database, search indexer, Java service, or PHP worker pool, swap is only one lever. You may also need worker caps, database cache limits, or a larger VPS plan.
How to create a Linux swap file
Pick a swap size that fits the job you are trying to survive. For a small VPS, that usually means enough space for short pressure events, not a second pool of RAM for permanent use. Leave disk space for logs and recovery.
Replace the placeholder with the size you chose before running the commands.
SWAP_SIZE="SET_THIS_FIRST"
sudo fallocate -l "$SWAP_SIZE" /swapfile
sudo chmod u=rw,go= /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
Confirm that Linux is using the file.
swapon --show
free -h
Make it survive a reboot only after the temporary test behaves normally.
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
sudo findmnt --verify
The file permission step is not cosmetic. Linux should refuse unsafe swap files, and loose permissions are a bad habit on a multi-user server. Keep the swap file owned by root and readable only by root.
Choose a size without pretending it is science
There is no universal swap size that fits every VPS. The right amount depends on the workload, the disk, the provider’s I/O limits, and whether you need hibernation. On a server, hibernation is usually irrelevant.
Use workload behavior instead of folklore. A web app that occasionally spikes during deploys needs a different buffer from a database that keeps its working set hot all day. Swap should cover rare peaks, not normal demand.
For a VPS buyer, the uncomfortable question is cost. If a small plan needs swap every day, a larger RAM tier may be cheaper than diagnosing repeated stalls. Compare the next plan at the provider page before spending hours tuning.
Tune the risk, not the benchmark
Linux swappiness controls how readily the kernel uses swap. A lower value usually makes sense for a VPS that should prefer RAM and use swap as a last buffer. Do not tune it blindly to chase a generic benchmark.
Check the current value first.
cat /proc/sys/vm/swappiness
Set a conservative value for the current boot if you know why you are changing it.
sudo sysctl vm.swappiness=10
Persist it only after observing real behavior under load.
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-vps-swap.conf
sudo sysctl --system
The important metric is not whether swap exists. It is whether latency, queue depth, and OOM logs improve without turning the disk into a memory crutch.
When to upgrade instead
Upgrade RAM or reduce the workload when swap is active during ordinary traffic, when the OOM killer still appears, or when disk latency climbs after you enable swap. Those are capacity symptoms, not setup mistakes.
For providers such as Hostinger, Hetzner, and IONOS, compare the next VPS tier against the time you would spend nursing a too-small server. The cheapest plan is rarely cheap after lost orders, failed deploys, or manual recovery.
Checklist
- Memory pressure: check free RAM and active swap during peak traffic, with persistent swap use treated as a capacity risk.
- Disk headroom: leave enough free storage after creating the file, with log growth and backups inspected before reboot.
- OOM history: review kernel messages after the change, with any repeated OOM event treated as an upgrade signal.
- Provider plan: compare the next RAM tier before deep tuning, with recurring operational stalls counted as real cost.
Freshness and method
HostScout treats swap as an operational decision, not a provider ranking trick. The provider examples above come from the current VPS catalogue available to our comparison data, while the Linux steps are standard server-administration practice. Prices and plan contents should be checked on the provider page before purchase.
FAQ
Is a swap file the same as more RAM?
Should every VPS have swap enabled?
Can swap damage an SSD?
Why did my VPS still run out of memory after adding swap?
Prepared by
Dedicated servers and small-business DevOps
He compares dedicated servers, unmanaged VPS plans, support promises, and the real cost of keeping a stack online.
Verified facts
HostScout editorialRelated articles
Fix Slow MySQL Queries Without Guessing
Fix slow MySQL queries with a measured workflow: find the real statement, read EXPLAIN safely, test one index or rewrite, and verify the workload.
Website Builders Compared by What You Keep
Website builders compared by ownership, export, hosting, commerce, recurring cost, accessibility, performance, and support before you commit.
Fix WordPress Plugin Conflicts Safely
Fix WordPress plugin conflicts without guessing: isolate the cause on staging, preserve rollback, read useful logs, and verify the whole site.
Self-host n8n on a VPS: a safe setup plan
Self-host n8n on a VPS with persistent Docker storage, TLS, correct webhook URLs, credential protection, backups, and a tested update plan.
What Is a Website? What It Needs to Go Live
What is a website? Learn how pages, domains, DNS, hosting, browsers, security, renewals, and backups fit together before you launch.
What Is an Email Alias and When to Use One
What is an email alias? Learn how aliases route mail, when they beat a mailbox, and what to check before choosing email hosting.