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.
Need a server to try this on? Antihost offers Linux VPS plans with NVMe storage, full root access and a 14-day free trial.
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.
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:
#1 Best Overall
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.
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 -hand 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.
Rank #2
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.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →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.
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.
Rank #4
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.
PC 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 & 11Outdated 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 match- Preallocation is not the same as suitability: a file produced by
fallocatemay 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-fillingddmethod 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.
Best Value
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:
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.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.
Recommended Free Tools
Troubleshoot the common failures
swapon: ... invalid argument
- Check whether the file is sparse, hole-filled, or otherwise unsuitable. Recreate it with
ddso every block is populated. - Check the filesystem type and kernel support, especially on copy-on-write filesystems.
- Confirm that
mkswapcompleted on the same path you pass toswapon. - Inspect the distribution’s
swapon(8)documentation for filesystem-specific restrictions.
Swap disappears after reboot
- Check that
/etc/fstabcontains the exact swap entry and that the path or identifier matches the active area. - Run
sudo swapon --allmanually; its error output usually identifies a syntax, path, or device problem. - Inspect
swapon --show,cat /proc/swaps, andfree -hafter 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 --showto see which files or devices are active. - Use
/proc/swapswhen a service or boot process needs the kernel’s authoritative list. - Use
free -hto 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.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Scan for outdated or missing drivers - takes under a minute3Repair Windows errors before they cause bigger problemsQuick Recap
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.




