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 DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
VGSources
Blog

How to Add Swap Space on a Linux VPS

A practical Linux VPS guide to creating, activating, verifying, and persisting swap, with filesystem cautions, partition and LVM alternatives, sizing guidance, and recovery steps.
Length10 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To add swap on a Linux VPS, first confirm that no swap is already active, then create a suitably sized file, restrict it to mode 0600, initialize it with mkswap, enable it with swapon, verify the result, and add an /etc/fstab entry so it returns after reboot. A swap file is usually the least disruptive option because it uses existing disk space; a partition or LVM volume is appropriate only when your provider exposes suitable block storage.

What swap is and why a VPS might need it

Swap is disk-backed storage that the Linux kernel can use as an extension of physical memory. It can provide breathing room when a game server, database, web panel, backup job, or other workload reaches its available RAM. It is not a replacement for RAM: disk access is far slower, and sustained swapping usually indicates that the VPS needs more memory or a lighter workload.

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.

On a VPS, a swap file consumes the same virtual disk allocated to the operating system and applications. Creating a large file can therefore leave too little room for game worlds, logs, package updates, databases, or backups. The correct size depends on workload, current memory pressure, free disk space, and any storage limit imposed by the provider. The official procedures for Ubuntu and Red Hat describe how to create and activate swap, but do not establish a universal sizing formula.

Check the VPS before creating anything

Log in through SSH as root, or use an account that can run sudo. Inspect active swap and available memory first:

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.
swapon --show
free -h

You can also inspect the kernel’s list directly:

cat /proc/swaps

If swapon --show or /proc/swaps already lists a device or file, swap is active. Do not create a second area automatically. Multiple swap areas can be intentional, but adding one without understanding the existing configuration makes capacity and troubleshooting harder. Check free disk space as well:

df -h

Leave enough capacity for the operating system and the data your VPS serves. If the volume is nearly full, delete or archive unneeded files, or expand the VPS volume before attempting to create swap.

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

Choose a swap size based on evidence

There is no single correct swap size for every VPS. A small game server with occasional memory spikes has a different requirement from a large modded server, build system, or database. Use these questions to choose a conservative value:

  • How much RAM is installed, and how much is normally free during peak activity?
  • Which process causes memory pressure, and is the pressure occasional or continuous?
  • How much disk space remains after reserving room for the OS, updates, logs, worlds, databases, and backups?
  • Does the VPS plan or provider impose a storage quota?
  • Will swapping merely absorb short spikes, or are you relying on it to run a workload that consistently exceeds RAM?

Replace the example 1G below with a size your disk can accommodate. Treat the result as an emergency buffer, not permission to overcommit memory indefinitely. After activation, monitor free -h, /proc/swaps, and your VPS monitoring system during the workload that caused the problem.

Create and activate a swap file

The following sequence works on common Ubuntu and Debian VPS installations and follows the operational stages documented by Ubuntu and Red Hat. Run each step as root or prefix it with sudo.

1. Allocate the file

The usual method is fallocate:

sudo fallocate -l 1G /swapfile

This creates a file named /swapfile at the root of the filesystem. Choose another path only if you understand which filesystem will hold it and can keep that path stable. Confirm the file exists and has the expected size:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
ls -lh /swapfile
df -h /

If swapon later rejects the file, or your filesystem does not provide a directly usable preallocated layout, create a fully populated file with dd instead:

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed
sudo dd if=/dev/zero of=/swapfile bs=1M count=1024 status=progress

With bs=1M and count=1024, this example writes approximately 1 GiB. Change count if you selected a different size. The command can take longer than fallocate because it writes every block.

2. Restrict permissions

Swap may contain pages from applications and users. Restrict the file so only root can read or write it:

sudo chmod 600 /swapfile
ls -l /swapfile

The listing should show permissions equivalent to -rw-------. Ubuntu and Red Hat both use this protection step. Do not skip it merely because the file is not intended for ordinary reading.

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.

3. Write the swap signature

Initialize the file as a Linux swap area:

sudo mkswap /swapfile

The mkswap manual defines this operation as setting up a Linux swap area on a device or in a file. It only writes the swap metadata; it does not start using the area.

4. Activate it

Tell the kernel to use the newly initialized file:

sudo swapon /swapfile

If this command succeeds, the area is active immediately. If it reports invalid argument, stop and investigate the file layout and filesystem before trying repeatedly.

5. Verify activation

Check all three views so you can distinguish an active area from a merely initialized file:

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

The first two commands should list /swapfile and its size. In free -h, the Swap row should show the configured total and currently used amount. Swap usage may remain at zero until the kernel needs it; that is normal and does not mean activation failed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)

Make the swap survive a reboot

Manual activation with swapon lasts only until the system is restarted unless the area is listed in /etc/fstab. Open the file with your preferred editor and add exactly one line:

/swapfile none swap defaults 0 0

Save the file, then test the entries without rebooting where supported:

sudo swapon --all
swapon --show

If swapon --all prints an error, correct the /etc/fstab line before rebooting. A missing, misspelled, or malformed entry is the usual reason swap appears to disappear after a restart. Reboot only after the test succeeds, then run swapon --show and free -h again to confirm that boot-time activation worked.

Filesystem behavior can determine whether a file works

A swap file must be directly usable by the kernel. Merely creating a file of the right apparent size is not enough if the underlying filesystem uses holes, delayed allocation, or copy-on-write behavior that swapon cannot accept.

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

Debian’s swapon(8) documentation records filesystem-specific restrictions and notes that preallocated swap files are supported on XFS since Linux 4.18. That version statement does not make every XFS, kernel, or mount configuration interchangeable. Check the kernel and filesystem documentation for your VPS, especially when using a copy-on-write filesystem.

A sparse or hole-filled file can look large in a directory listing while not having all blocks physically allocated. If a file created with fallocate is rejected, recreate it with the fully populated dd command shown above, apply chmod 600 again, rerun mkswap, and then retry swapon. Do not copy an unsuitable sparse file into active use and assume that its displayed size proves it is valid.

The sequence matters: mkswap initializes, while swapon activates. Running only the first command leaves a dormant file that will not provide memory relief.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

Use a partition or LVM volume when block storage is available

A dedicated swap partition or logical volume avoids placing swap inside a regular filesystem. This option requires a suitable block device exposed by the VPS provider or an existing volume group with free space. Changing a partition layout can be operationally risky, so do not alter the boot disk casually.

Dedicated device

After identifying the correct unused device, initialize and activate it:

sudo mkswap /dev/your-device
sudo swapon /dev/your-device

Substitute the real device path; never paste the placeholder literally. Choosing the wrong device can destroy data. Verify the result:

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

Add the device to /etc/fstab so it is enabled at boot. A stable identifier appropriate to your distribution is preferable to a device name that could change, although the exact identifier command and syntax depend on the VPS layout. Test with sudo swapon --all before rebooting.

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

LVM logical volume

Red Hat’s documented LVM flow is to create a logical volume in the available volume group, run mkswap on that logical volume, add it to /etc/fstab, reload mount units when needed, activate it with swapon, and verify through /proc/swaps and free -h. Use the logical-volume path exposed by your system, for example:

sudo mkswap /dev/your-volume-group/your-logical-volume
sudo swapon /dev/your-volume-group/your-logical-volume

Follow your distribution’s LVM tooling and confirm every path before running commands. The volume must be dedicated to swap; initializing a volume that contains application data will make that data inaccessible.

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

Both forms provide a swap area once initialized and activated. The practical differences are operational rather than a universal performance ranking.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.
Consideration Swap file Partition or LVM volume
Provider requirement Uses existing filesystem space; no separate block device is required. Requires an exposed dedicated device or free LVM capacity.
Initial setup Create a file, set mode 0600, run mkswap, then swapon. Prepare the device or logical volume, then run mkswap and swapon.
Resizing Usually easier to replace with a differently sized file after disabling it. Depends on partition or LVM operations and the provider’s storage controls.
Filesystem compatibility Must satisfy the kernel and filesystem’s swap-file rules; sparse or unsuitable layouts fail. Not subject to regular-file allocation rules because the swap area is the block device itself.
Persistence Use a /swapfile entry in /etc/fstab. Use the device path or, preferably, a stable identifier in /etc/fstab.
Operational risk Normally avoids partition edits, but consumes application disk space. Partition changes can threaten existing data; an incorrect device selection is destructive.

The cited Ubuntu and Red Hat procedures do not establish that one form is universally faster. Select the form your storage layout supports and that you can maintain safely.

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.

Troubleshoot common failures

swapon: ... invalid argument

  • Check that the file is not sparse or hole-filled. Recreate it with dd if a preallocated file was rejected.
  • Confirm the filesystem supports swap files under your kernel and mount configuration.
  • Ensure mkswap completed after the final file was created and before swapon was run.
  • Inspect the complete error from swapon and consult the swapon(8) documentation for filesystem-specific restrictions.

Swap is missing after reboot

  1. Run grep -n swap /etc/fstab and confirm the intended line is present and syntactically correct.
  2. Run sudo swapon --all manually and read any error it prints.
  3. Check that the path still exists with ls -l /swapfile, or that the device identifier resolves.
  4. Verify with swapon --show and free -h after correcting the configuration.

The VPS has no disk space

Swap cannot exceed available storage. Remove unused files, rotate or archive oversized logs, or expand the VPS volume before creating a swap file. Do not consume the last free gigabytes and leave package updates or game data unable to write.

Another swap area is already active

Return to swapon --show and cat /proc/swaps. Decide whether the existing area is adequate before adding anything. If you intentionally need another area, document both entries in /etc/fstab and verify that each one activates cleanly.

The file has the wrong permissions

Run sudo chmod 600 /swapfile and verify with ls -l. Reapply the permission after recreating or replacing the file; a newly created replacement does not inherit the old file’s mode automatically.

Resize or remove a swap file safely

When a file is too small or consumes space you need elsewhere, replace it rather than editing it in place. First make sure the VPS has another active swap area or that a maintenance window can tolerate temporarily having none.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Disable the current file: sudo swapoff /swapfile.
  2. Remove the old file: sudo rm /swapfile.
  3. Delete or update its line in /etc/fstab so boot does not reference a nonexistent path.
  4. Create the replacement with fallocate, or use dd when filesystem behavior requires a fully populated file.
  5. Run chmod 600, mkswap, and swapon in that order.
  6. Verify with swapon --show, /proc/swaps, and free -h, then test sudo swapon --all.

For a partition or LVM volume, resizing involves storage-management operations specific to that layout; do not run generic file commands against a block device.

Monitor the result on a game-serving VPS

After activation, observe the VPS during its busiest realistic period: player joins, world saves, scheduled backups, updates, and any plugins or mods that increase memory use. Use free -h for a quick snapshot, swapon --show or cat /proc/swaps to confirm the configured area, and the provider’s monitoring graphs to identify recurring pressure.

A swap total that remains unused can be a sign that the VPS has adequate RAM, not a configuration problem. Conversely, continuously rising swap use, severe latency, or processes being killed indicates that adding disk-backed memory did not solve the underlying capacity issue. Reduce the workload, tune the application, or move to a VPS with more RAM rather than treating swap as unlimited memory.

Essential command sequence

For a conventional filesystem where fallocate is accepted, the complete minimal workflow is:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
swapon --show
free -h
sudo fallocate -l 1G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
swapon --show
cat /proc/swaps
free -h
printf '%sn' '/swapfile none swap defaults 0 0' | sudo tee -a /etc/fstab
sudo swapon --all

Use the dd allocation method instead when the filesystem or swapon rejects the preallocated file. Always check the final /etc/fstab entry and leave sufficient disk for the operating system and applications.

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 quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.