...

How to Add a Swap File to an Ubuntu VPS and Configure Swappiness

Martin Klein

Reading time 1 minute

On an Ubuntu VPS, you can add swap as a regular file without creating a separate disk partition.

The basic procedure is as follows:

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

To enable swap after a reboot, add the following to /etc/fstab: /swapfile none swap sw 0 0

You can check the current memory and swap status using:

 free -h
swapon --show
vmstat 1

For a VPS, you can further reduce vm.swappiness, for example to 10, if you want the system to be less inclined to move memory pages to swap: sudo sysctl vm.swappiness=10

To make the setting persistent, save it in /etc/sysctl.d/99-swappiness.conf.

Before resizing swap, make sure there is enough available RAM to run swapoff. If swap is actively in use, disabling it when memory is nearly full can be dangerous.

A small amount of swap usage is normal. However, consistently full swap, low available memory, and regular nonzero si/so values in vmstat indicate that the server most likely does not have enough RAM.

What Swap Is and When You Actually Need It

Welcome!

Today, we’ll cover a relatively straightforward topic—but one that people often start looking into only after their first unpleasant surprise on a VPS.

For example, the server seems to be running normally, there is enough memory, and the application is responding—then a brief load spike occurs, some process suddenly consumes the remaining RAM, and Linux’s OOM killer starts terminating processes, usually the most important ones.

This is when you turn to swap.

Swap is an area on disk that Linux can use as additional memory space when RAM is running low.

However, it is important to clear up a common misconception right away: swap is not a “free extension of RAM.”

It can help a server survive a memory shortage, but for obvious reasons, disk storage is not as fast as RAM—so swap is a fallback, not a “free” RAM extension.

In this article, we will not only create a swap file but also explore when swap is actually useful, how to choose its size, what swappiness does, and why constantly full swap is no reason to celebrate that “everything is working.”

How Swap Relates to RAM

RAM is the primary workspace for processes.

It stores:

  • Program code;
  • Application data;
  • Cache;
  • Process memory pages;
  • Temporary kernel data structures.

As long as there is enough RAM, everything runs quickly.

Problems begin when available memory runs low.

Linux can move less frequently used memory pages to swap, freeing up RAM for more immediate tasks.

For example, if a process has not accessed a particular region of memory for some time, the kernel can temporarily move it to swap.

When that data is needed again, Linux reads it back into RAM.

This is where the performance difference between RAM and disk becomes apparent.

RAM is significantly faster than even a good SSD or NVMe drive. Therefore, frequent, sustained swap activity can significantly slow down a server.

For this reason, swap is best viewed not as a full replacement for memory, but as a safety net.

Swap is particularly useful when a server normally operates within its available RAM but occasionally experiences brief load spikes.

When Swap Helps and When to Add More Memory

Swap is particularly useful in several scenarios.

For example, a VPS with 1–2 GB of RAM may run a small application, Nginx, a database, and several background processes.

Most of the time, everything fits in memory.

However, any of the following may occasionally occur:

  • Package updates;
  • Application builds;
  • Importing a large file;
  • A spike in requests;
  • A temporary increase in cache size;
  • Starting an additional process.

Without swap, the server can quickly reach its RAM limit.

The kernel will then have to free memory in other ways, potentially even terminating processes through the OOM killer.

In this situation, a small amount of swap can give the system some breathing room and help it handle the spike without the application crashing.

However, if the server constantly uses most of its swap, the situation is different.

For example:

 RAM: 2 GB
Swap: 4 GB
RAM used: 1.9 GB
Swap used: 3.2 GB

And this is the case almost all the time.

This does not mean that we have magically turned a VPS with 2 GB of memory into one with 6 GB.

Rather, the server simply does not have enough RAM.

A particularly bad sign is the constant active writing of data to swap and reading it back, combined with an overall slowdown in business applications.

In this state, the system may become noticeably slower because processes must constantly wait for disk I/O instead of accessing memory at high speed.

The rule is therefore quite simple:

  • Occasional or low swap usage is normal;
  • Using swap during a short-lived spike is beneficial;
  • Consistently full swap indicates that memory usage needs to be investigated;
  • Constant active swapping is a sign that it is time to add more RAM or reduce the workload.

In other words, swap helps mitigate memory shortages, but does not eliminate the physical limitations of the VPS.

Checking Memory and Current Swap

Before creating a new swap file, let’s check what is already configured on the server.

Some providers configure swap automatically. In other cases, no swap is configured at all.

We will also assess the current state of the server’s RAM.

Checking RAM with free

The simplest command: free -h

The option -h displays values in a human-readable format: megabytes and gigabytes instead of bytes.

For example:

Several columns are particularly useful here.

  • Total — the total amount of RAM.
  • Used — the amount of memory currently in use.
  • Free — completely unused memory.

Linux avoids leaving RAM unused unnecessarily and actively uses it for caching.

Therefore, to estimate the actual headroom, it is generally more useful to look at: available

This is the approximate amount of memory that the system can make available to new processes without making significant use of swap.

For example, if:

free = 200 MB

available = 1.1 GB

This does not necessarily mean that the server is nearly out of memory.

Some of the RAM is simply being used for useful cache data that can be released when needed.

Checking Active Swap

Now let’s check whether swap is enabled at all: swapon --show

If the command produces no output, there is currently no active swap.

You can double-check using: free -h

If you see: Swap: 0B  0B  0B, then swap is indeed absent.

If swap has already been set up, swapon --show may display output similar to the following:

The fields are:

FieldDescription
NAMEPath to the swap file or partition
TYPESwap type
SIZETotal size
USEDAmount currently in use
PRIOPriority when multiple swap areas are available

You can also view the data directly using: cat /proc/swaps

However, swapon --show is generally more convenient for routine checks.

Another useful command: vmstat 1

It will update the statistics every second.

Later, we will focus particularly on the si and so columns:

Here:

  • si — data read from swap into RAM;
  • so — data written from RAM to swap.

If these values are almost always zero, the server is not actively swapping at the moment.

If the values increase continuously under normal load, the server may already be running short of memory.

We now know how much memory the VPS has and whether swap is currently configured.

If swap is not configured or its current capacity is insufficient, the next step is to create a regular swap file, set the correct permissions, and enable it without creating a separate disk partition, which is simpler and safer in a VPS environment.

Creating a Swap File

Allocating Space for Swap

Suppose we want to create 2 GB of swap space.

The easiest way is to use: sudo fallocate -l 2G /swapfile

The command will create the file: /swapfile with a size of 2 GB.

Let’s check: ls -lh /swapfile

Expected output: -rw-r–r– 1 root root 2.0G … /swapfile

If fallocate is unsuitable for the file system in use for any reason, you can create the file using dd: sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress

The result will be the same: a file approximately 2 GB in size will be created on the disk.

Before creating swap space, make sure the partition has enough free space: df -h /

If the disk is nearly full, allocating several more gigabytes for swap without first checking the available space is not a good idea.

Configuring Permissions

Now for the most important step: restricting access to the file.

Run: sudo chmod 600 /swapfile

Let’s check: ls -lh /swapfile

The permissions should now look approximately like this: -rw——- 1 root root 2.0G … /swapfile

Why are permissions set to 600 here?

Swap may contain memory pages from processes. Memory can potentially contain sensitive data, such as tokens, passwords, request contents, and other values.

Therefore, regular users must not be able to read this file.

Permissions: 600 means:

  • The owner can read and write;
  • All other users have no access.

This is a normal and expected permission setting for a swap file.

Format and Enable Swap

A large file alone does not constitute swap space.

First, you need to mark it as swap space: sudo mkswap /swapfile

After that, we will see a message similar to the following: Setting up swapspace version 1, size = 2 GiB

Now enable it: sudo swapon /swapfile

Let’s check: swapon --show

Expected output:

Let’s also check the total memory: free -h

The Swap line should now show the configured capacity:

Swap: 2.0Gi 0B 2.0Gi

It is perfectly normal if USED is currently zero.

Swap does not have to be used immediately after it is enabled. It simply becomes available to the kernel when needed.

Making Swap Permanent

Swap is now working, but one issue remains.

The command: sudo swapon /swapfile enables it only for the current system session.

After the VPS reboots, the file will remain on disk, but it will no longer be used automatically as swap space.

To prevent this, add the swap file to /etc/fstab.

Adding swap to /etc/fstab

File: /etc/fstab contains information about file systems and other resources that Linux should mount at boot.

Before editing, it is advisable to create a backup: sudo cp /etc/fstab /etc/fstab.bak

Now open the file: sudo nano /etc/fstab

And add the following at the end: /swapfile none swap sw 0 0

Let’s review the fields:

ValueMeaning
/swapfilepath to the swap file
noneno mount point is required for swap
swapresource type
swstandard swap options
0 0dump and fsck are not required for swap

Save the file.

Carefully check the line before rebooting.

Verifying the Configuration After a Reboot

First, let’s make sure that swap is currently active: swapon --show

You can then reboot the VPS: sudo reboot

After reconnecting, check: swapon --show and free -h

If /swapfile is shown as active again, the entry in /etc/fstab is working, and swap is enabled automatically.

You can also check the line: grep swap /etc/fstab

Expected: /swapfile none swap sw 0 0

Swap no longer requires you to run swapon manually after every reboot.

Configuring swappiness

Swap has already been created, enabled, and configured to persist across VPS reboots.

Now all that remains is to decide, how readily Linux should use it at all.

This is controlled by the parameter: vm.swappiness

There is another common misconception here.

swappiness is not the “percentage of RAM usage at which swap is enabled.”

In other words, a value of: 10 does not mean “start using swap when only 10% of memory remains.”

The parameter works differently.

What the vm.swappiness Parameter Means

vm.swappiness controls how readily the Linux kernel moves inactive memory pages to swap instead of keeping them in RAM.

You can check the current value as follows: cat /proc/sys/vm/swappiness or sysctl vm.swappiness

For example: vm.swappiness = 60

The higher the value, the more readily the system may use swap.

The lower the value, the longer the kernel tries to keep data in RAM.

For a typical VPS, a more moderate value, such as 10 or 20, is often used.

However, there is no single universally correct value.

If the server runs a database, web application, or other latency-sensitive processes, it is generally best to avoid overly aggressive swapping.

On the other hand, setting 0 is not always advisable either.

This does not mean that swap is completely disabled. Rather, the system will simply be extremely reluctant to use it.

For a small VPS, 10 may therefore be a reasonable starting point; you can then monitor how it performs under the actual workload.

Changing the Value Temporarily

Let’s try changing swappiness without rebooting: sudo sysctl vm.swappiness=10

Let’s check: sysctl vm.swappiness

Expected: vm.swappiness = 10

The change takes effect immediately.

However, it remains in effect only until the next reboot.

This is useful for testing: you can observe how the server behaves under normal load and choose a different value if necessary.

Making the Setting Persistent

To make the swappiness setting persist after a reboot, create a dedicated sysctl file: sudo nano /etc/sysctl.d/99-swappiness.conf

Add: vm.swappiness=10

Save the file.

You can apply the setting without rebooting as follows: sudo sysctl --system

After that, let’s check again: sysctl vm.swappiness

It should remain: vm.swappiness = 10

After the next reboot, the system will automatically load this value as well.

Swap is now available, and the kernel’s behavior when using it has been configured.

One practical question remains: how much swap space should be allocated?

How to Choose the Swap Size

There is no universal formula.

The old rule that swap should be twice the size of RAM is too simplistic for modern VPSs.

The appropriate size depends on how much memory the server has, the workload, and why swap is being created in the first place.

Some Practical Guidelines

For a typical VPS, the following values are a reasonable starting point:

VPS RAMReasonable initial swap size
1 GB1–2 GB
2 GB1–2 GB
4 GB1–4 GB
8 GB1–4 GB
16 GB or moreDepends on the workload

For a small server that occasionally experiences brief memory spikes, 1–2 GB of swap often provides a useful safety buffer.

However, if a VPS has:

  • RAM = 2 GB
  • Swap = 8 GB

And most of that 8 GB is regularly in use, the problem is no longer an incorrectly sized swap.

The server most likely does not have enough RAM.

For databases and applications under sustained heavy load, consider not only the total swap size but also how actively it is being used.

Another distinct use case is hibernation.

Hibernation is rarely relevant on a typical VPS, so there is usually no need to allocate swap equal to or greater than RAM for this purpose.

In a server environment, swap primarily protects against brief memory spikes and provides additional memory capacity; it is not a full replacement for RAM.

Increasing or Decreasing Swap Space

The swap size does not have to be fixed once and for all.

If you later find that 1 GB is insufficient and 4 GB is excessive, you can recreate the swap file with a different size.

But there is an important caveat: you cannot simply delete an active swap file and create a new one.

First, disable swap properly, but before doing so, make sure the system has enough RAM.

Checking Whether There Is Enough RAM for swapoff

Command: sudo swapoff /swapfile moves pages in use from swap back to RAM.

If there is not enough RAM at this point, the system may hang, slow down significantly, or encounter an OOM condition.

So first, we check: free -h

Pay particular attention to:

available

Swap used

For example, if swap is using 1.5 GiB, and the available RAM is down to just 400 MiB, disabling swap right now is a bad idea.

It is best to first:

  • Stop resource-intensive processes;
  • Wait for the system load to decrease;
  • Temporarily increase the VPS RAM allocation, if the provider allows it;
  • Alternatively, create additional swap space before modifying the primary swap.

If swap is barely being used and there is enough free memory, you can proceed.

Disabling swap and resizing the file

Suppose we want to increase the swap size from 2 GB to 4 GB.

First, disable the current swap file: sudo swapoff /swapfile

Verify: swapon --show

If /swapfile no longer appears in the list, it is no longer active.

Now let’s delete the old file: sudo rm /swapfile

And create a new one: sudo fallocate -l 4G /swapfile

The same process applies when reducing the size.

For example, if we want 1 GB: sudo fallocate -l 1G /swapfile

After creating it, be sure to restore secure permissions: sudo chmod 600 /swapfile

Let’s check: ls -lh /swapfile

Reformat and remount it

The new file must once again be converted into swap space: sudo mkswap /swapfile

Then enable it: sudo swapon /swapfile

Check swapon --show and free -h

If the path remains unchanged: /swapfile, you do not need to modify the entry in /etc/fstab.

It will continue to work: /swapfile none swap sw 0 0

After resizing, however, it is a good idea to verify once again that the entry is actually present: grep swap /etc/fstab

Only then should the change be considered complete.

Checking Whether Swap Helps the Server

Simply having swap configured does not necessarily mean that the server is now running well.

Once configured, monitor memory for a while to see exactly how the system uses this reserve.

Check RAM and swap usage

Let’s start with a familiar command: free -h

For example:

220 MB of swap in use does not necessarily indicate a problem.

Linux may move pages that have not been used for a long time to swap and leave them there even if RAM becomes available again later.

Therefore, it is more important to look not only at Swap used, but at swap activity.

To do this: vmstat 1

The columns we are interested in are:

  • si
  • so

Where:

  • si — pages moved from swap back to RAM;
  • so — pages moved from RAM to swap.

If the server shows the following values most of the time:

  • si = 0
  • so = 0

while some swap space is in use, this is usually not a cause for concern.

You can also view the active swap: swapon --show

When Active Swapping Indicates Insufficient Memory

You should be concerned when several of the following signs appear at the same time:

  • Available RAM remains consistently very low;
  • Swap remains consistently full;
  • si and so are regularly nonzero;
  • Applications begin responding more slowly;
  • The load average increases;
  • OOM messages appear.

You can check for OOM events as follows: sudo journalctl -k | grep -i oom or dmesg | grep -i oom

If the system continuously moves data back and forth between RAM and swap, this results in a phenomenon known as thrashing.

At this point, the server begins spending too much time on disk I/O instead of processing requests.

In this situation, increasing the swap size further does not always help.

If the problem persists, it is better to:

  • Add more RAM;
  • Reduce the number of worker processes;
  • Limit resource-intensive services;
  • Identify the process with a memory leak;
  • Optimize the application or database.

In other words, swap is useful as a safeguard and buffer.

However, if it becomes the server’s primary workspace, the problem is no longer a lack of swap space but insufficient RAM.

Conclusion

Swap on an Ubuntu VPS is a useful safeguard against temporary memory shortages, but it cannot turn a small server into a large one.

We created a swap file, set secure permissions, enabled it with swapon, added it to /etc/fstab, and configured vm.swappiness. We also covered how to resize swap safely and how to distinguish normal swap usage from a situation in which the server is constantly running up against its memory limit.

The key rule here is simple: do not look at the Swap used figure alone.

If some swap space is in use but si and so are almost always zero, that alone is not a problem. However, continuous swapping between RAM and swap, low available memory, and poor performance indicate that the server most likely does not have enough RAM.

In other words, swap works well as a buffer and reserve for peak demand. However, if an application begins to rely on it continuously, it is time to consider adding more RAM or optimizing the workload.

FAQ

Can a server run without swap?

Yes.

If the VPS has enough RAM and the workload is stable, the server can run normally without swap.

However, a small amount of swap is often useful as an additional safeguard against temporary spikes and unexpected out-of-memory (OOM) conditions.

Why is swap already in use when RAM is still available?

This is normal.

Linux may leave long-unused pages in swap and use the freed RAM for more useful purposes, such as the file cache.

A nonzero Swap used value does not by itself indicate a problem.

Which Is Better: a Swap File or a Dedicated Swap Partition?

For a typical VPS, a swap file is usually more convenient.

It is easier to do the following:

  • Create it;
  • Increase its size;
  • Reduce its size;
  • Delete it;
  • Move it.

A dedicated swap partition makes sense in more specialized scenarios, but a swap file is perfectly suitable for most virtual servers.

Can I set vm.swappiness=0?

Yes, but this does not disable swap completely.

This setting simply makes the kernel very reluctant to use swap.

For a typical VPS, a value around 10–20 is often chosen and then evaluated under the actual workload.

Does swap need to be twice the size of RAM?

No, this is not a universal rule.

For modern VPS instances, the swap size should be based on the workload.

For example, a server with 2 GB of RAM often needs only 1–2 GB of swap, while a machine with 16 GB of RAM does not necessarily need an additional 32 GB.

What happens if you run swapoff when RAM is nearly exhausted?

The system will attempt to move the pages currently in swap back into RAM.

If there is not enough RAM, the server may slow down significantly, become unresponsive, or encounter an out-of-memory (OOM) condition.

Therefore, before running swapoff, always check free -h and determine whether there is enough available RAM.

Can swap be stored on an SSD or NVMe drive?

Yes. In fact, this is a common setup on a VPS.

However, even a fast NVMe drive is still significantly slower than RAM, so active swapping should not be considered normal operation under sustained load.

How can you tell whether swap is actually helping?

In addition to observable outcomes—such as the absence of crashes and OOM events—you can examine actual metrics. Look not only at total swap usage, but also at: vmstat 1

If si and so are usually zero and a small amount of swap is occasionally in use, this is normal.

If the values regularly increase, RAM is almost always fully utilized, and applications slow down, swap is no longer helping so much as masking a memory shortage.

Sources

  1. Ubuntu Server Documentation — Swap
  2. Linux Kernel Documentation — Swappiness
  3. man7.org — swapon(8)
  4. man7.org — fstab(5)

Subscribe to our newsletter and receive articles and news

    Check out our other materials