Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk9 min

How to Add Swap Space on a Linux VPS (Safely and Permanently)

A practical Linux VPS swap guide covering safe sizing, the swap-file workflow, filesystem restrictions, persistent /etc/fstab configuration, partition and LVM alternatives, and troubleshooting.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The safest way to add swap on most Linux VPSs is to create a swap file on the existing volume, lock its permissions to 0600, initialize it with mkswap, activate it with swapon, verify the result, and add it to /etc/fstab so it returns after a reboot. First check whether swap is already active; creating a second area unnecessarily consumes disk space and can complicate troubleshooting.

What swap space does on a VPS

Swap is a disk-backed Linux memory area. The kernel can use it when physical RAM is under pressure, giving processes somewhere to move less-active memory pages. It is slower than RAM, so adding swap does not turn a small VPS into a larger-memory machine. It can, however, provide emergency headroom and reduce the chance that a short-lived memory spike immediately exhausts RAM.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A swap area is either a file inside an existing filesystem or a separate block device such as a partition or an LVM logical volume. Linux does not use either automatically just because it exists: the area must be initialized and then activated. The Ubuntu mkswap manual describes the command as setting up “a Linux swap area on a device or in a file”; it also notes that swapon is required before the area is used.

Check the VPS before creating anything

Do not begin by creating /swapfile. An image, hosting template, or previous administrator may already have enabled swap. Inspect the current state first:

swapon --show
free -h

swapon --show lists active swap areas, their type, size, amount in use, and priority. free -h gives a human-readable summary of RAM and swap totals. You can also inspect the kernel’s view directly:

cat /proc/swaps

If an existing area provides enough capacity for the workload, you may not need another one. If you do add capacity, record what is already active so that you can distinguish the new area from the old one during verification.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose a size without a misleading formula

There is no universal “correct” swap size in the documented procedures. Choose a value using four practical constraints:

  • Workload: a build, database, indexing job, or memory-heavy service may need more emergency headroom than a small static site.
  • Available disk: a swap file occupies real VPS storage. Leave room for the operating system, logs, package caches, databases, uploads, and temporary files.
  • Current memory pressure: use free -h and your VPS monitoring history to see whether RAM exhaustion is occasional or constant.
  • Provider limits: the VPS plan may cap the disk volume or restrict which block devices are available.

A one-time example is a 1 GiB file, but that is a command example rather than a recommendation for every server. Replace the size with a value your workload and free space justify. Check free storage before allocating it:

df -h /

If the root filesystem has little free space, remove genuinely unused data or expand the VPS volume first. Swap cannot be created larger than the storage available on the target filesystem.

Create a swap file step by step

This workflow works on common Ubuntu and Debian VPS installations and is also consistent with the operational stages documented by Red Hat. Run as root, or prefix each command with sudo.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

1. Allocate the file

The usual method is fallocate. The following creates a 1 GiB file at /swapfile:

sudo fallocate -l 1G /swapfile

Use a different path only if it is on a filesystem you have checked and the path will remain available during boot. The file is not swap yet; at this stage it is merely storage reserved for the future swap area.

2. Use a fully populated file when required

Some filesystem layouts or swapon implementations reject files that contain holes or are otherwise unsuitable for direct kernel use. If fallocate produces an “invalid argument” error at activation time, remove the unusable file and create a fully populated one with dd:

sudo rm -f /swapfile
sudo dd if=/dev/zero of=/swapfile bs=1M count=1024 status=progress

Here, count=1024 with bs=1M writes approximately 1 GiB of zero-filled data. Adjust the count when you choose another size. This approach takes longer because it writes every block, but it avoids the sparse or hole-filled layout that can prevent activation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

3. Restrict permissions

Swap can contain pages from processes and may therefore hold sensitive data. Make the file readable and writable only by root:

sudo chmod 600 /swapfile

Verify the mode if you want an explicit check:

ls -l /swapfile

The permissions should show root-only access (for example, -rw-------). Do this before initializing or activating the area.

4. Write the swap signature

Initialize the file with mkswap:

sudo mkswap /swapfile

The command writes the metadata that identifies the file as a Linux swap area. It does not turn swapping on; activation is a separate step.

5. Activate it immediately

sudo swapon /swapfile

If the command succeeds, the kernel can use the new area now. Activation does not by itself make the setting survive a reboot, so complete the persistence step below.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

6. Verify the active area

Use more than one view when diagnosing a new setup:

swapon --show
cat /proc/swaps
free -h

You should see /swapfile in the first two outputs and a non-zero total swap value in free -h. A zero “used” value immediately after activation is normal; it means the kernel has not needed to move pages there yet.

Make the swap file survive a reboot

Linux systems normally list swap areas in /etc/fstab so the boot process can activate them. Open the file with an editor and add exactly one line:

/swapfile none swap defaults 0 0

Save the file, then test the entries without rebooting:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo swapon --all

On a correctly configured system this command returns without an error and leaves the swap area active. If it reports a problem, fix the /etc/fstab line before relying on the next reboot. Recheck with:

swapon --show
free -h

Do not add duplicate lines for the same file. Duplicate or malformed entries can produce confusing boot-time messages and make it unclear which definition is being used.

Filesystem details that can make or break activation

A swap file must be directly usable by the kernel. The fact that a regular file can be created does not guarantee that swapon accepts its layout. Filesystem-specific restrictions are documented in the Debian swapon(8) manual.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Preallocation is not the same as suitability: a file produced by fallocate may still be rejected if the filesystem represents it with holes or unsupported extents.
  • Copy-on-write filesystems need special care: snapshots, compression, and delayed allocation can affect whether a file is valid for swap. Check the filesystem and kernel documentation before relying on the fast allocation path.
  • XFS version matters: the Debian manual records support for preallocated swap files on XFS since Linux 4.18. That is a version-linked capability, not a guarantee for every XFS configuration or every older kernel.
  • Do not copy a sparse file into service: a file that appears large in a directory listing but does not have all blocks allocated can fail at swapon. Recreate it with the zero-filling dd method if necessary.

When you are unsure, check the filesystem type and kernel version, then consult the distribution’s swapon(8) documentation. The safest recovery from a layout error is to deactivate and remove the failed file, recreate it fully populated, initialize it again, and retry activation:

sudo swapoff /swapfile
sudo rm -f /swapfile
sudo dd if=/dev/zero of=/swapfile bs=1M count=1024 status=progress
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

Only run swapoff for a path that is actually listed as active. If the VPS is already short of RAM, turning off its only swap area can increase memory pressure; schedule the replacement promptly.

Use a partition or LVM volume instead

A file is usually the least disruptive choice on a VPS because it does not require repartitioning. A separate partition or LVM logical volume is appropriate when the provider exposes suitable block storage and you deliberately want swap outside the main filesystem.

Dedicated partition or block device

First identify the correct device. Never guess a device path: selecting the wrong one can destroy data. Once verified, initialize and activate it:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo mkswap /dev/your-device
sudo swapon /dev/your-device

Add the device to /etc/fstab so it is enabled at boot. A stable identifier is preferable to a device path that can change between boots; use the identifier format appropriate to your distribution. Then test:

sudo swapon --all
cat /proc/swaps
free -h

LVM logical volume

With LVM, the documented sequence is to create a logical volume in an existing volume group, initialize it with mkswap, add it to /etc/fstab, reload mount units when the distribution requires it, activate it with swapon, and verify it through /proc/swaps and free -h. The exact logical-volume creation command depends on the names and free extents in your volume group, so confirm those values before running a destructive storage command.

Unlike a file, a partition or logical volume is not subject to the containing filesystem’s file-allocation rules. It does, however, require block storage that the VPS provider actually exposes and carries more operational risk if partition boundaries or volume-group data are changed incorrectly.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Swap file versus partition or LVM volume

Decision axis Swap file Partition or LVM volume
Provider requirement Uses free space in an existing mounted filesystem. Requires a suitable exposed block device, partition, or LVM volume.
Initial setup Create a file, set mode 600, run mkswap, run swapon, and add an /etc/fstab entry. Initialize the device with mkswap, activate it, and add a device or stable-identifier entry to /etc/fstab.
Resizing Generally easier: replace the file with one of a different size after safely deactivating the old area. Depends on partition or LVM operations and the storage layout.
Filesystem dependency Must satisfy the filesystem and kernel rules for a directly usable, non-sparse file. Uses a block device directly, avoiding file-allocation restrictions.
Persistence /swapfile none swap defaults 0 0 in /etc/fstab. A device path or, preferably, a stable identifier in /etc/fstab.
Operational risk No partition-table change; the main risk is consuming too much filesystem space or using an unsupported file layout. Changing partitions or LVM carries greater risk of affecting existing data if the wrong device or extent is selected.

Neither the Ubuntu nor Red Hat procedures establish a universal performance ranking between these choices. Select based on storage access, filesystem compatibility, resizing needs, and the risk you can safely manage.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshoot the common failures

swapon: ... invalid argument

  • Check whether the file is sparse, hole-filled, or otherwise unsuitable. Recreate it with dd so every block is populated.
  • Check the filesystem type and kernel support, especially on copy-on-write filesystems.
  • Confirm that mkswap completed on the same path you pass to swapon.
  • Inspect the distribution’s swapon(8) documentation for filesystem-specific restrictions.

Swap disappears after reboot

  1. Check that /etc/fstab contains the exact swap entry and that the path or identifier matches the active area.
  2. Run sudo swapon --all manually; its error output usually identifies a syntax, path, or device problem.
  3. Inspect swapon --show, cat /proc/swaps, and free -h after correcting the entry.

There is not enough disk space

Stop the allocation and check df -h. Remove unused files only when you know they are safe to delete, or expand the VPS volume. A swap file cannot be larger than the free storage available on its filesystem, and reserving nearly all remaining space can leave the operating system and applications unable to write logs or data.

An existing swap area is already active

Return to swapon --show before adding anything else. Multiple areas can be intentional, but adding one blindly wastes storage and makes capacity and usage harder to interpret. Decide whether the existing area is insufficient, then document the reason for any additional area.

Operational checks after setup

Keep the verification commands available for routine monitoring:

swapon --show
cat /proc/swaps
free -h
  • Use swapon --show to see which files or devices are active.
  • Use /proc/swaps when a service or boot process needs the kernel’s authoritative list.
  • Use free -h to compare total, used, and available RAM and swap in a readable format.
  • Use your VPS monitoring system to correlate swap use with application memory pressure and disk capacity.

Swap activity is a signal to investigate memory demand, not proof that the VPS has adequate performance. If the system repeatedly exhausts RAM and spends substantial time swapping, reduce application memory use or move to a plan with more physical memory rather than treating disk-backed swap as a permanent substitute.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.