iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
Need a server to try this on? Antihost offers Linux VPS plans with NVMe storage, full root access and a 14-day free trial.
To add swap space on a Linux VPS, first confirm that no suitable swap area is already active, then create a swap file, restrict it to mode 0600, initialize it with mkswap, activate it with swapon, verify the result, and add an /etc/fstab entry so it returns after a reboot. A swap file is usually the least disruptive option because it uses existing disk space and does not require repartitioning.
Swap can absorb temporary memory pressure, but it is storage rather than RAM. It is much slower than physical memory, consumes VPS disk capacity, and cannot compensate indefinitely for an undersized plan or a memory leak. The procedure below applies to common Ubuntu, Debian and Red Hat Enterprise Linux-compatible VPS distributions; exact provider restrictions and filesystem behavior still need to be checked on your server.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →What swap does on a VPS
Linux uses swap as a disk-backed extension of virtual memory. When memory pressure rises, the kernel can move less-active pages out of RAM and write them to a configured swap area, leaving RAM available for active processes. If those pages are needed again, they are read back from storage.
This makes swap useful as a safety margin for short bursts such as package upgrades, builds, database maintenance or a temporary increase in web traffic. It does not make a VPS perform like one with more RAM. Heavy swapping can produce high latency, and a VPS with sustained memory pressure normally needs workload tuning, a smaller application footprint or a larger memory plan.
#1 Best Overall
Swap also uses your VPS volume. A swap file therefore reduces the disk space available for the operating system, logs, databases, containers and user data. Check available capacity before choosing a size.
Check whether swap already exists
Do not create a second area before inspecting the current configuration. Multiple swap areas can be valid, but adding one unnecessarily consumes storage and makes troubleshooting harder.
swapon --show
free -h
cat /proc/swaps
swapon --show lists active areas in a readable table. cat /proc/swaps shows the same kernel-level view, while free -h reports total, used and available memory and swap in human-readable units. If an existing area is listed and provides enough capacity for the workload, you may not need to add anything.
Run the commands as root or prefix them with sudo. You also need enough free disk space for the proposed file and permission to edit /etc/fstab. On a managed VPS, check whether the provider limits swap or already maintains it through its image or control panel.
Choose a swap file or a partition/LVM volume
A swap file is normally the practical first choice on a VPS because it can be created inside an existing filesystem without changing a partition table. A dedicated partition or logical volume is appropriate when the provider exposes spare block storage or when your storage layout already reserves a swap device.
| Decision point | Swap file | Partition or LVM volume |
|---|---|---|
| Required storage | Free space inside an existing filesystem. | A dedicated block device, partition or logical volume exposed by the VPS. |
| Creation effort | Create, initialize and activate one file; no repartitioning. | Prepare the device or create the logical volume, then initialize and activate it. |
| Resizing | Usually easier: deactivate the old file, replace it with a different-sized file, and update persistence if its name changes. | Depends on the partition or volume layout and may require storage changes that carry more operational risk. |
| Filesystem considerations | The file must have a layout the kernel accepts; sparse or hole-filled files and some copy-on-write arrangements can fail. | Not dependent on an ordinary data-file layout, although the device must be suitable block storage. |
| Boot persistence | Add a file entry to /etc/fstab. |
Add the device path or, preferably, a stable device identifier to /etc/fstab. |
| Performance conclusion | No universal performance advantage is established by the documented procedures; actual results depend on the VPS storage stack. | No universal performance advantage is established by the documented procedures; actual results depend on the VPS storage stack. |
Changing partitions on a running VPS carries more risk than creating a file. Use a partition or LVM volume only when you understand the provider’s block-device layout and have a recovery path.
Recommended Free Tools
Rank #2
Choose a size without a fake universal formula
There is no single correct swap size for every Linux VPS. The official Ubuntu and Red Hat procedures describe how to configure swap but do not prescribe a workload-independent sizing formula. Select a size using the application’s peak memory demand, current RAM, observed memory pressure, available disk and any provider limits.
Check the constraints first
- Use
free -hto see RAM and currently configured swap. - Use your provider’s disk view or
df -hto confirm free space on the filesystem where the file will live. - Leave room for system updates, logs, databases, container layers and application data. A swap file should not consume the capacity those workloads require.
- Decide whether you need an emergency buffer for occasional spikes or are trying to support sustained memory overcommit. The latter generally calls for a larger VPS or workload changes.
The commands in the standard example use 1G as an adjustable example. Replace that value with a size your workload and disk can support; it is not a recommendation for every server. After activation, monitor free -h, /proc/swaps and your VPS monitoring data to determine whether the chosen capacity is actually useful.
Create and enable a swap file
The following sequence works on a typical Linux VPS when /swapfile is placed on a filesystem that supports swap files. Execute each stage as root or with sudo.
1. Create a fully sized file
The quickest method is fallocate:
sudo fallocate -l 1G /swapfile
This requests a 1 GiB file named /swapfile. Change 1G to the size you selected. If the filesystem or the local swapon implementation rejects a file created this way, use a fully populated file made with dd instead:
sudo dd if=/dev/zero of=/swapfile bs=1M count=1024 status=progress
Here, count=1024 with a 1 MiB block size creates approximately 1 GiB. Adjust the count when you choose another size. The command writes the blocks rather than relying on allocation behavior that some filesystems handle differently.
2. Restrict access to the file
sudo chmod 600 /swapfile
Mode 0600 allows only the owner, normally root, to read or write the file. This matters because pages moved to swap can contain sensitive application or user data. Ubuntu and Red Hat examples both apply this permission before activation.
3. Write the swap signature
sudo mkswap /swapfile
mkswap sets up a Linux swap area on a device or in a file. It initializes metadata; it does not start using the area. The Ubuntu mkswap manual explicitly states that swapon is required after creation.
4. Activate the area
sudo swapon /swapfile
If this command completes without an error, the kernel can use the file immediately. Activation is separate from both file creation and mkswap, so omitting it leaves the file inactive.
5. Verify activation
swapon --show
cat /proc/swaps
free -h
Look for /swapfile in the first two outputs and a nonzero swap total in free -h. The displayed amount can differ slightly from the decimal size you typed because tools report binary and decimal units differently.
6. Make the configuration persistent
Open /etc/fstab with your preferred editor and add this line exactly:
/swapfile none swap defaults 0 0
The first field is the file path, none indicates that this is not a normal mounted filesystem, swap identifies the type, and defaults supplies standard options. The final two zeroes disable dump and filesystem-check processing that does not apply to a swap area.
Save the file, then test the entry without rebooting:
Rank #4
sudo swapon --all
swapon --all reads swap entries from /etc/fstab and activates those not already active. If it reports an error, fix the line before relying on a future reboot. Re-run swapon --show and free -h after a successful test.
Filesystem details that can make a swap file fail
A swap file must be directly usable by the kernel. A file that appears to have the requested length but contains holes or an unsupported allocation layout may be rejected by swapon. This is why the dd fallback is important when fallocate produces an invalid argument or similar error.
Filesystem support is version-specific. Debian’s swapon(8) documentation records that preallocated swap files are supported on XFS since Linux 4.18; that statement does not make every XFS configuration or every other copy-on-write filesystem universally suitable. Check the running kernel and filesystem documentation before depending on fallocate.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchPC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Identify the filesystem holding the file
findmnt -T /swapfile
The output identifies the mount and filesystem type for the path. Run it after creating the file if you need to confirm where the file resides. If the path is on a filesystem with swap-file restrictions, create the file on a supported filesystem or use a dedicated block device instead.
Avoid copying a sparse file into swap use
Do not treat a swap file like an ordinary sparse or hole-filled data file. Copying, truncating or converting it can change its physical layout even when its apparent size remains unchanged. If you replace it, create a new fully allocated file, initialize it with mkswap, activate it, and verify it before removing the old area.
Use a dedicated partition or LVM swap volume
Use this method only when your VPS exposes a suitable unused device or lets you create a logical volume. Never run mkswap on a device that contains a mounted filesystem or valuable data; it writes a swap signature and makes the previous contents unusable as a normal filesystem.
Best Value
Prepare and activate a device
sudo mkswap /dev/your-device
sudo swapon /dev/your-device
swapon --show
cat /proc/swaps
free -h
Replace /dev/your-device with the actual device path. Confirm the path with your provider’s documentation and local block-device inventory before running the command.
Persist the device safely
Add the device to /etc/fstab. A stable identifier is preferable to a path whose device name could change between boots. The exact identifier syntax depends on the distribution and device metadata, so use the identifier exposed by your system rather than copying an example blindly.
Red Hat’s documented LVM flow is: create the logical volume, run mkswap, add it to /etc/fstab, reload mount units when required by the system, activate it with swapon, and verify it with /proc/swaps and free -h. The same separation of initialization, persistence and activation applies whether the backing storage is a logical volume or a partition.
Confirm persistence after a reboot
A swap area that works now can disappear after reboot if it was never listed in /etc/fstab or if that line contains a typo. Before scheduling maintenance, test the entry with sudo swapon --all and inspect any error text. After a reboot, run:
swapon --show
cat /proc/swaps
free -h
If the area is absent, inspect /etc/fstab for the exact path, device identifier, type and option fields. Correct the entry, run sudo swapon --all again, and verify that the corrected area appears. Do not add duplicate lines for the same file or device.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Resize or remove a swap file safely
Swap files do not have an in-place size setting that you can change while active. To replace one, plan the change during a period when the VPS has enough free RAM and disk space.
- Add and activate a new file with the desired size and a different temporary path, following the creation, permission, initialization and verification steps above.
- Update
/etc/fstabso that the new path is the persistent entry. - Deactivate the old area with
sudo swapoff /old/pathonly after confirming that the system can operate without it. - Remove the old file after
swapon --showconfirms that it is no longer active, then test the final/etc/fstabconfiguration withsudo swapon --all.
If the old area is heavily used, swapoff can take time or fail because RAM is insufficient. Do not force removal; reduce memory use, stop nonessential workloads or resize the VPS first.
Quick Recap
Troubleshoot common errors
| Symptom | Likely cause | What to check or do |
|---|---|---|
swapon: ... invalid argument |
Unsupported filesystem behavior, a sparse or hole-filled file, or an unsuitable file layout. | Check the filesystem with findmnt -T /swapfile, review swapon(8) restrictions, recreate the file with dd, then run mkswap and swapon again. |
| Swap works until reboot, then disappears | Missing or malformed /etc/fstab entry. |
Confirm the exact path or stable identifier, run sudo swapon --all, and inspect the error before rebooting again. |
| There is not enough space to create the file | The VPS volume lacks free capacity. | Check disk usage, remove only verified-unneeded files, expand the volume through the provider, or choose a smaller size that still meets the workload’s needs. Never fill the volume so completely that the operating system cannot write logs or updates. |
| An existing swap area is already listed | Swap is active, so another area may be unnecessary. | Review swapon --show, /proc/swaps and free -h before adding capacity. |
mkswap succeeds but no swap appears |
The area was initialized but not activated. | Run sudo swapon /swapfile or the appropriate device command, then verify. |
| The file is readable by other users | Permissions were not restricted. | Run sudo chmod 600 /swapfile and verify the mode before activation. |
| The provider’s image already manages swap | A control panel or provisioning system may recreate or remove entries. | Check provider documentation and avoid conflicting automation or duplicate /etc/fstab lines. |
Operational and security checks after activation
- Keep the swap file at mode
0600; swapped pages can contain credentials, session data or other sensitive memory contents. - Monitor both swap usage and remaining disk space. A swap area that is almost full and a root filesystem that is almost full are separate risks.
- Interpret occasional swap use differently from continuous heavy activity. Occasional use can provide resilience during a spike; sustained use indicates memory pressure that swap alone does not solve.
- Record the file path or device identifier in your configuration management so a rebuild reproduces the intended setting.
- Keep a VPS recovery or console path available before changing partitions, logical volumes or boot-time storage configuration.
Key commands at a glance
# Inspect current state
swapon --show
free -h
cat /proc/swaps
# Create a 1 GiB file (adjust the size)
sudo fallocate -l 1G /swapfile
# Fully populated fallback if required
sudo dd if=/dev/zero of=/swapfile bs=1M count=1024 status=progress
# Secure, initialize and activate
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
# Persist and test
# Add: /swapfile none swap defaults 0 0
sudo swapon --all
swapon --show
free -h
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.

