DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
VGSources
Blog

How to Clear Swap Memory on a Linux Server Safely

Safely clear swap on a Linux server with swapoff and swapon, check RAM headroom first, verify the result, and understand why drop_caches and swappiness are different tools.
Length8 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To clear swap on a Linux server, first confirm that RAM can hold the swapped pages, then run sudo swapoff -a followed by sudo swapon -a. The first command moves pages from swap back into RAM; the second re-enables every swap device and file configured in /etc/fstab. Check free -h before and after. If available RAM is insufficient, swapoff can stall, fail, or trigger memory exhaustion, so do not run it blindly on a busy production host.

Swap clearing is different from dropping the filesystem page cache and different again from changing swappiness. The sections below separate those operations, show when each is appropriate, and provide recovery steps when a server cannot evacuate swap safely.

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.

What “clearing swap” means

Linux uses swap as backing storage for memory pages that are not currently resident in physical RAM. A server can show swap in use even when it is operating normally: the kernel may have moved cold pages out of RAM to preserve space for active processes and filesystem cache. A non-zero swap-used value is therefore not, by itself, proof of a fault.

Clearing swap means evacuating those pages into RAM and temporarily disabling the swap areas. The standard sequence is:

sudo swapoff -a
sudo swapon -a

swapoff -a applies to all active swap areas. It must find enough usable RAM to receive the pages it is moving. swapon -a then activates the swap partitions and files listed in /etc/fstab. The swap capacity returns, but the “used” amount should be near zero immediately after the migration.

This is an operational reset, not a performance cure. Linux normally reclaims memory and manages swap without manual intervention. If you repeatedly need to clear swap, investigate memory sizing, a leaking process, workload spikes, or an unsuitable storage and swappiness configuration instead of treating the symptom.

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.

Check memory headroom before disabling swap

Do these checks in the shell that has administrative privileges:

  1. Record the current memory view:

    free -h

    Read the available value in the Mem: row, not only the free column. “Available” is the kernel’s estimate of RAM that can be given to applications without swapping heavily. Record the Swap: row as your baseline.

  2. List every configured swap area and its current use:

    swapon --show

    This identifies whether swap is a partition, a file, or several areas. It also prevents a surprise when swapon -a later activates more than one entry.

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  3. Look for a process consuming most of the available RAM. Use your normal process monitor, or sort a one-time listing with:

    ps -eo pid,comm,%mem,rss --sort=-%mem | head

    If available RAM is already low, stop or reschedule a safe workload before attempting the migration. Do not rely on swap as the destination for pages you are trying to remove from swap.

As a practical safety test, the amount of resident RAM that must be available is roughly related to the swap pages currently in use, plus working room for the kernel and applications. The relationship is not exact because pages may be shared, compressed, or reclaimed during the operation. Leave a margin rather than assuming that “available RAM equals swap used” is sufficient.

Clear all swap areas step by step

1. Quiesce memory-heavy work

Pause large builds, database maintenance, backups, or batch jobs if you can. A server that allocates aggressively while pages are being moved has less headroom and is more likely to hit the out-of-memory path.

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

2. Disable swap and observe the result

sudo swapoff -a

The command may take time while pages are copied back to RAM. In another terminal, watch memory:

watch -n 1 free -h

Do not start a second swapoff while the first is still running. If the command returns successfully, the Swap: row should show zero used and zero total until swap is enabled again.

3. Re-enable the configured swap

sudo swapon -a

This reads the swap entries enabled in /etc/fstab. It does not create a new swap area and does not automatically activate an ad-hoc device that is absent from that file. If you intentionally disabled only one area, re-enable that same path explicitly instead:

sudo swapon /path/to/swapfile

Use the exact device or file name shown by swapon --show.

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

4. Verify capacity and usage

free -h
swapon --show

The swap-used figure should be zero or very small immediately after reactivation. The total should match the areas that were successfully enabled. A missing total usually means an entry in /etc/fstab failed validation, the device is unavailable, or permissions and file setup do not meet the kernel’s requirements.

If swapoff hangs or fails

A stalled operation generally means the system cannot find enough reclaimable RAM to receive all swapped pages. Treat that as a capacity warning, not as a command that should be forced through.

  • Check the live figures: run free -h and inspect the largest processes. If available RAM is falling, stop nonessential work before trying again.
  • Look for an error message: retain the exact output from swapoff. It may identify a particular device or an inability to allocate memory.
  • Reduce demand first: stop a known memory-heavy service using that service’s normal, reversible procedure. Avoid killing an unknown process merely to make the command complete.
  • Do not reboot as a first response: rebooting discards the diagnostic state and can turn a controlled memory shortage into an outage. Plan a maintenance window if the host cannot maintain headroom.
  • Escalate the underlying issue: repeated failures indicate that the server needs more RAM, a lower-memory workload, or investigation of a leak. Clearing swap is not a substitute for correcting that condition.

If swapoff -a succeeds but swapon -a reports an error, leave the host running while you inspect the specific swap entry. Confirm that the device exists, the file path is correct, and the entry in /etc/fstab has the intended type and options. Re-enable a known-good area explicitly only after confirming the path.

Clear one swap area instead of everything

On a server with multiple swap devices or files, you may need to evacuate only one area for maintenance. First identify the exact target:

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

Then disable and re-enable that path:

sudo swapoff /dev/your-swap-device
sudo swapon /dev/your-swap-device

For a swap file, substitute its absolute path. This still requires enough RAM for the pages currently residing on that area. A device-by-device approach reduces the scope of the change but does not remove the headroom requirement.

Confirm that you cleared swap, not the page cache

Swap and filesystem cache are different memory consumers. The swapoff/swapon sequence moves swapped anonymous pages into RAM. It does not deliberately remove clean file data from the page cache.

If your goal is to test application behavior with a cold cache, use the kernel’s cache-control interface instead. Flush pending writes first:

sync

Then choose the level that matches the test:

Command Objects affected Use
echo 1 | sudo tee /proc/sys/vm/drop_caches Clean page cache Remove cached file contents
echo 2 | sudo tee /proc/sys/vm/drop_caches Reclaimable slab objects, including dentries and inodes Remove filesystem metadata caches
echo 3 | sudo tee /proc/sys/vm/drop_caches Both page cache and reclaimable slab objects Clear both categories for a controlled test

sync matters because dirty objects cannot be freed by drop_caches until their data is written. Dropping cache does not cap future cache growth; Linux will build the cache again as files are read. Use it manually for diagnostics or benchmarking, not as a routine memory-management job.

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

Kernel messages emitted when caches are dropped are informational. The control value uses bits 1 and 2 for the two cache classes; writing value 4 (bit 2) suppresses those messages, but it does not itself free cache. Do not confuse that logging bit with a cache-clearing level.

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

Use swappiness to change future behavior

vm.swappiness is a policy setting, not a clearing command. It expresses the relative I/O cost of swapping versus paging filesystem data on a scale from 0 to 200. The documented default is 60. A value of 100 treats the two costs as equal; lower values make swap appear more expensive, so the kernel tends to preserve anonymous pages in RAM, while higher values make swap appear cheaper.

Setting direction Kernel preference When it may fit
Lower than 60 Prefer keeping application pages in RAM and reclaim filesystem cache sooner Workloads where latency from swapped application pages is especially harmful
60 Default balance Starting point when you have no workload evidence for a change
100 Treat swapping and filesystem paging as equal-cost choices Systems where those I/O paths have similar costs
Above 100 Make swap look relatively inexpensive Some in-memory swap or hybrid setups, such as zram, zswap, or swap on storage faster than the filesystem workload

Inspect and change the live value with:

sysctl vm.swappiness
sudo sysctl -w vm.swappiness=20

The second command lasts until the next reboot. To persist a chosen value, create a file such as /etc/sysctl.d/99-swappiness.conf containing:

vm.swappiness = 20

Then load the configuration:

sudo sysctl --system

Choose a value through measurement and workload testing, not by copying a generic “best” number. Memory cgroups can apply a group-specific policy that overrides the global setting, so a container or service may behave differently from the host.

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

zram, zswap, and compressed swap considerations

Not all swap is a disk partition or ordinary swap file. Some distributions use compressed RAM devices such as zram, and systems may use zswap as a compressed front end. On those configurations, disabling swap can require decompressing pages back into regular RAM. The resulting RAM spike can be substantial even when the swap device itself is small.

Identify the implementation before a production change:

swapon --show
cat /proc/swaps

If the type or device name indicates compressed swap, test the exact procedure on a non-production host with a similar memory limit. Keep a console or out-of-band access path available in case the host becomes unresponsive. The ordinary swapoff -a/swapon -a sequence still describes the operation, but its memory impact is different from evacuating pages from a disk-backed area.

When clearing swap is appropriate

  • Planned storage maintenance: evacuate a swap device before replacing, resizing, or detaching it, provided the host has sufficient RAM.
  • Controlled diagnostics: establish a known starting point for a memory or latency test, then record the workload and cache state so results are comparable.
  • Post-incident cleanup: remove stale swapped pages after a temporary memory spike, once the host has ample headroom.
  • Routine monitoring alerts: do not clear swap simply because a graph is non-zero. Examine pressure, latency, available RAM, and process behavior first.

If a server is under sustained memory pressure, adding physical RAM, reducing concurrency, moving a workload, or fixing a leak is usually safer than repeatedly cycling swap. A swap reset can make the graph look clean while leaving the cause untouched.

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

Operational checklist

  1. Schedule the change and ensure console or out-of-band access.
  2. Run free -h and record available RAM and swap used.
  3. Run swapon --show to enumerate every swap area.
  4. Pause avoidable memory-heavy work.
  5. Run sudo swapoff -a and wait for it to complete.
  6. Run sudo swapon -a to restore configured capacity.
  7. Verify with free -h and swapon --show.
  8. Investigate any failure before repeating the operation.
  9. Use sync and drop_caches only when the objective is page-cache testing, not swap clearing.
  10. Tune vm.swappiness only after observing the workload, and document any persistent sysctl.d change.

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
Windows Errors? Fix Them Before They SpreadFree repair scan
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.