VPS.TC
| $
Server Status
Turkey Istanbul, Türkiye
Active
USA New York, USA
Active
Cart Total:
View Cart
How to Create Swap Space on a VPS for Linux Memory Management
Linux

How to Create Swap Space on a VPS for Linux Memory Management

Avatar of Defne Defne August 30, 2026 14 min read 0 Comments
Share:

Creating Swap Space on a VPS Without Hiding the Real Problem

When a VPS slows down at night, CPU is rarely the first thing I check. I open top, look at a few processes, and then inspect the memory columns. If the CPU is mostly idle but applications take too long to respond, memory pressure may be the real problem. Restarting the service immediately can do little more than silence the alarm.

That is where swap helps. When RAM gets tight, Linux can move some memory pages to a reserved area on disk. Disk is nowhere near as fast as RAM, so swap is not a replacement for memory. It is a safety valve for a short memory spike, and it can give the kernel more room before the OOM killer starts choosing victims.

🚀 Boost Your Speed with VPS Server!

Speed up your projects with high-performance SSD storage and 99.9% uptime guarantee.

Get Started

Creating swap on a VPS usually takes only a few commands. The careful part comes before and after them: I check existing swap areas, file permissions, the persistent /etc/fstab entry, and the provider’s virtualization policy. The mistake I see most often is creating the file and forgetting persistence. After a reboot, the file still exists, but it is no longer active.

Linux memory is more than the RAM marked free

You can divide Linux memory into broad categories: anonymous memory, file cache, and memory used by the kernel. A PHP-FPM worker generally uses anonymous pages, while files read from disk may remain in the page cache. That is why treating buff/cache in free output as wasted memory gives you the wrong diagnosis.

free -h

Typical output may look like this:

☁️ Gain Flexibility with Cloud Server!

Experience the power of cloud with scalable resources and instant backups.

Explore
               total        used        free      shared  buff/cache   available
Mem:           3.8Gi       2.1Gi       180Mi       120Mi       1.5Gi       1.3Gi
Swap:          1.0Gi       128Mi       896Mi

I pay particular attention to available. The free number can be small while available memory remains healthy, because Linux can release part of the file cache when an application needs it. Seeing some swap usage is not automatically a crisis either. The useful question is whether the machine is continuously reading from and writing to swap at a high rate.

As memory pressure grows, the kernel can drop caches that are easy to rebuild. If that is not enough, it may move anonymous pages to swap. When RAM and swap still cannot satisfy demand, the OOM killer terminates a process. On a production server, you would rather not discover that the chosen process was your database or web server.

What swap can and cannot fix

Swap can buffer a sudden memory spike on a small VPS. A compression job during a backup is one example: it may briefly need more memory than usual, and swap may help keep it alive.

But disk is much slower than RAM. If the system is constantly swapping, application latency increases, I/O wait rises, and the VPS begins to feel heavy. Adding an even larger swap file is not a permanent fix. I first find the process using the memory, stop unnecessary services, or move the workload to a larger VPS.

That distinction matters.

Observation Likely meaning First check
Swap is in use, but available memory is high Pages that had not been touched for a while may have been moved to disk free -h and the change over time
Swap usage keeps increasing There may be memory pressure or a memory leak vmstat 1 and process RSS values
RAM and swap are both full OOM risk is very high Kernel journal entries and service limits
Swap I/O is very busy The system is using disk instead of RAM iostat and application logs

See the machine before changing it

You can run these commands as root. I still prefer sudo where possible. It is not magical protection against using the wrong terminal, but it makes the intent visible. My production shells have red prompts for the same reason.

First, confirm where you are.

hostnamectl --static
free -h
swapon --show
cat /proc/swaps
lsblk -f

If swapon --show returns nothing, there may be no active swap. Some providers deliver VPSs with swap already configured; others restrict swap at the virtualization layer. Check the provider’s documentation before creating another one. Activating the same space twice is not useful.

Measure disk space too:

df -h /
findmnt -no FSTYPE,OPTIONS /

If the swap file will live on the root filesystem, it needs enough free space. The filesystem matters as well. Swap files generally work without trouble on ext4 and XFS on modern Linux installations. Btrfs has extra requirements: copy-on-write must be disabled for the file, and its layout must be suitable for swap. I would not apply a generic swap-file recipe to Btrfs without checking the distribution’s documentation first.

Creating a swap file on Ubuntu and Debian

The following example creates a 2 GiB /swapfile. Your workload may need a different size. Automatically adding 4 GiB of swap to every VPS with 512 MiB of RAM is not a sound rule; measuring the actual memory use of the running services is better.

Allocate the file

sudo fallocate -l 2G /swapfile
ls -lh /swapfile

fallocate is fast, but its result depends on the filesystem. If it fails, or if you are working on an environment where you do not trust the allocation behavior, use dd instead:

sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress

This can be slower because it writes zeroes to the file. With bs=1M and count=2048, the result is approximately 2 GiB. Check the destination twice. A typo in of= can be expensive.

Restrict the file permissions

sudo chmod 600 /swapfile
ls -l /swapfile

The expected permissions are approximately -rw-------. Swap may contain pages moved out of process memory, so leaving it readable by everyone is not appropriate. And no, chmod 777 is not a universal permissions fix; it only turns a configuration problem into a larger security problem.

Format and enable it as swap

sudo mkswap /swapfile
sudo swapon /swapfile
sudo swapon --show
free -h

mkswap writes a swap signature to the file, while swapon makes it available to the kernel. If /swapfile appears in swapon --show, activation worked.

If you see a warning such as swapon: /swapfile: insecure permissions, apply chmod 600 first. An Operation not permitted error may mean that the virtualization provider does not allow guest-level swap. Check the VPS type and support documentation instead of trying random commands.

Keep it active after a reboot

Add this single line to /etc/fstab:

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Before appending anything, I check for existing swap entries:

grep -nE '[[:space:]]swap[[:space:]]' /etc/fstab
sudo systemctl daemon-reload
sudo swapoff /swapfile
sudo swapon -a
sudo swapon --show

The daemon-reload command is harmless here but is not what reads /etc/fstab; swapon -a does that job. The last three commands test the entry without rebooting. If swapoff fails because there is not enough RAM, inspect free -h before trying again. I have made the mistake of treating a test step as routine maintenance; on a busy production server, forcing it can make the original problem worse.

There is no magic swap-size number

Tables based only on RAM size are easy to find online. They can be starting points, but they are not decisions. A web server, database, container workload, and compilation job all have different memory profiles.

When choosing a size, I look at available memory during busy periods, peak process usage, and remaining disk capacity. One or two GiB may be enough to absorb a brief increase of a few hundred MiB. Running a large database while depending on swap is postponing a performance problem.

For example, 1 GiB of swap can be a reasonable safety margin on a 2 GiB VPS running Nginx and a small application. If the same machine runs Elasticsearch, MariaDB, and several containers, I adjust service memory limits first. The service and security order in Launch a Secure VPS in 30 Minutes | Pro Admin Guide is also useful when checking a new VPS setup.

Adjusting Linux’s willingness to swap

The kernel’s vm.swappiness setting influences how readily Linux uses swap. On Linux kernels where this setting is available, its value ranges from 0 to 200. Exact behavior depends on the kernel and workload, but a lower value generally makes the kernel less eager to swap anonymous memory.

cat /proc/sys/vm/swappiness

To test a value of 10 temporarily:

sudo sysctl vm.swappiness=10

For a persistent setting, I prefer a separate file:

echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-memory.conf
sudo sysctl --system

Setting the value to 0 is usually not a good idea. I understand wanting to prevent swap, but that also removes room for maneuver when RAM is completely full. On low-memory application VPSs, I usually start with 10 or 20 and wait for monitoring data.

Changing swappiness the moment you notice swap usage is premature. Moving an untouched page to swap can leave more RAM available for the file cache. If application response times are normal, swap I/O is low, and available memory remains healthy, that behavior is not automatically a fault.

Watch first.

Finding the cause of heavy swap usage

A single free snapshot rarely tells you whether swap is causing the trouble. Sampling once per second with vmstat is more useful:

vmstat 1

In the output, si is swap-in and so is swap-out. If both remain consistently high, the system is under memory pressure. Do not panic over one short-lived value; persistence and application latency matter more.

To find the processes using the most memory:

ps -eo pid,user,comm,%mem,rss --sort=-rss | head -n 15
systemd-cgtop

rss approximates the physical memory held by a process and is reported in kilobytes. Because libraries can be shared, adding RSS values does not exactly reproduce total RAM usage. It is still useful for seeing which service is at the top of the list.

If you use Docker, inspect container memory too:

docker stats --no-stream

A memory limit can stop a container from growing without control. Setting that limit arbitrarily low only makes the container hit OOM sooner. Measure normal and busy workloads first.

Last month, application response times increased on a customer’s VPS even though free -h still showed some free memory. Regular si and so activity in vmstat 1 shifted my suspicion to swap, and the top of the ps list showed more PHP-FPM workers than expected. We reduced the worker count to match the application’s real traffic and watched the server for several hours. I did not enlarge the swap. The problem was an uncontrolled process pool, not a swap file that was too small.

Removing or resizing the swap file

If you created a swap file with the wrong size, you do not need to keep adding new files. Disable the active area, remove its fstab entry, delete the file, and create it again at the desired size.

sudo cp -a /etc/fstab /etc/fstab.bak
sudo swapoff /swapfile
sudo sed -i '|^/swapfile none swap sw 0 0$|d' /etc/fstab
sudo rm -f /swapfile

The sed command removes only the exact matching entry. The backup comes first on purpose. I once reached for sed before making that copy during a rushed maintenance window; the command was correct, but the habit was not.

If swapoff fails, inspect the RAM situation. Do not force an operation the server cannot currently handle.

Before deleting the file, confirm with swapon --show that the active swap has really been disabled. Mixing up an active old area with a new file of the same name is easy during a night intervention.

Details that matter in a VPS environment

Not all VPS platforms expose the same virtualization features. Some older OpenVZ-based environments do not allow you to create swap inside the guest. On a KVM-based VPS, a swap file on the virtual disk is more common, but the provider’s terms still apply.

If the disk containing the swap file fills up, other problems follow quickly. Watch df -h when logs, database files, backups, and swap share the same filesystem. When disk usage becomes critical, I use ncdu to find the growing directory first. Deleting random files without understanding their owner or application behavior is a reliable way to create a second incident.

Encrypting swap can be useful for some threat models. Consider what sensitive data may be moved there, especially if you do not know the provider’s disk-encryption, snapshot, and physical-access policies. Encrypted swap setup varies by distribution and by how keys are handled at boot, so I would follow the provider and distribution documentation rather than offer a copy-and-paste recipe that could leave the machine unable to boot.

Swap is not a backup. It is kernel workspace, not preserved application data. A swap file will not restore a database after a crash. For backups and access controls, pair this work with the relevant checks in 10 Essential Steps to Secure and Harden Your Linux Server.

When might ZRAM make more sense?

ZRAM creates a compressed block device in RAM and uses it as swap. It can reduce physical disk I/O and work well on small systems, but compression and decompression consume CPU. It is not an automatic replacement for a traditional swap file.

Adding ZRAM to a VPS that is already CPU-bound can make response times worse. On a lightly loaded system, compressed RAM may handle short memory spikes usefully. Check kernel and module support from the provider, then compare the result with monitoring data.

There is a trade-off.

What I check after setup

  • Does free -h show both RAM and swap?
  • Does swapon --show list the expected file or partition?
  • Does ls -l /swapfile show permissions of 600?
  • Is there one correct entry in /etc/fstab?
  • Does sudo swapoff /swapfile && sudo swapon -a complete successfully?
  • Do si and so stay consistently high during vmstat 1?
  • Does monitoring track RAM, swap, disk I/O, and OOM events?

I also check the kernel journal:

journalctl -k -b | grep -iE 'out of memory|oom|killed process'

Empty output is a good sign, but it does not prove that the machine will never hit OOM. If you use Uptime Kuma or Grafana and Prometheus, compare memory, swap, and disk I/O over the same time window. Putting process, traffic, and deployment records beside the graphs tells me more than staring at one metric alone.

The commands for creating swap are short; memory management takes more patience. My order is simple: measure first, add swap second, and then watch whether the situation improves. Swap can buy a server time. Constant swap activity is still the server asking for a different fix.

Frequently asked questions

How much swap should I create for a VPS?

There is no single correct size. Consider the VPS’s RAM, its services, and peak memory usage together. For a small application server, 1-2 GiB may be a reasonable starting point. Do not treat swap as a permanent answer to insufficient RAM.

Does swap usage make a VPS slower?

Heavy swap reads and writes can slow applications because disk is much slower than RAM. Short-lived, low swap usage can be normal. If si and so remain high in vmstat 1, investigate memory consumption.

Is a swap file better than a swap partition?

On modern Linux systems, a swap file is sufficient for most VPSs because it is easier to manage. A swap partition provides dedicated disk space, but changing its size later is more involved. Unless your provider offers a specific alternative, a file is the practical choice.

Why does my swap file disappear after a reboot?

The swapon command enables swap for the current session. If /etc/fstab does not contain /swapfile none swap sw 0 0, the file will not be enabled automatically after a reboot.

Avatar of Defne
Author

Defne