Cleaning up orphaned swap files that bloat disk space on a 2 GB VPS.

Orphaned Swap Files on a 2 GB VPS – How to Spot, Clean, and Harden

A 2 GB VPS is a tight budget. Every megabyte counts, and swap files that never get freed can silently eat the space you need for logs, containers, or backups. This post walks through how to find those orphaned swap files, safely remove them, and set up a swap strategy that keeps the system lean and secure.


Why Orphaned Swap Appears

Swap files are usually created by the installer or by systemd-swap when the kernel reports insufficient RAM. On a minimal VPS, the installer may leave a 1 GB swap file behind. If the system later boots with a larger RAM pool or the swap file is no longer referenced in /etc/fstab, the file remains on disk but is never mounted. The kernel simply ignores it, but the file still consumes space.

Common scenarios that lead to orphaned swap:

Scenario Typical cause Impact
Re‑installed OS New image with no swap entry Old swap file left behind
Manual swap removal swapoff -a + rm /swapfile File removed, but /etc/fstab still points to it
Container migration Swap file used by a VM, then VM deleted File remains on host
Kernel upgrade Swap file format changes Kernel ignores old file

Detecting Orphaned Swap Files

  1. List all swap devices and files

    swapon --show
    

    If nothing appears, the kernel isn’t using any swap.

  2. Check /etc/fstab

    grep -i swap /etc/fstab
    

    Any line that references a file or device that no longer exists is a candidate.

  3. Search for large unused files
    Swap files are often named /swapfile, /swap.img, or similar.

    find / -type f -size +100M -name '*swap*' 2>/dev/null
    
  4. Cross‑reference with lsblk
    If a block device is listed but not in swapon --show, it might be an orphan.

    lsblk -o NAME,SIZE,TYPE,MOUNTPOINT,ROTA
    
  5. Audit with df
    A quick sanity check:

    df -h
    

    If the root filesystem shows 1 GB used but you know the system has only 500 MB of actual data, suspect a swap file.


Safely Removing Orphaned Swap

Before deleting anything, confirm the file isn’t in use:

# Verify the file exists
ls -l /swapfile

# Verify it’s not mounted
swapon --show | grep /swapfile

If the file is not listed, it’s safe to remove. However, if you’re unsure whether a process might have opened it, use lsof:

lsof | grep /swapfile

An empty output means no process holds it.

Step‑by‑step removal

# 1. Disable any swap entry in /etc/fstab
sudo sed -i '/swapfile/d' /etc/fstab

# 2. Remove the file
sudo rm -f /swapfile

# 3. Verify disk space
df -h

If the file is a block device (e.g., /dev/sdb1), use fdisk or parted to delete the partition, then run partprobe to refresh the kernel’s partition table.


Re‑establishing Swap – Minimalist Approach

On a 2 GB VPS, you might want to keep swap but keep it small and secure.

  1. Create a small swap file

    sudo fallocate -l 512M /swapfile
    sudo chmod 600 /swapfile
    sudo mkswap /swapfile
    sudo swapon /swapfile
    
  2. Persist across reboots
    Add to /etc/fstab:

    echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
    
  3. Limit swap usage
    Edit /etc/sysctl.conf or create /etc/sysctl.d/99-swap.conf:

    vm.swappiness=10
    vm.vfs_cache_pressure=50
    

    swappiness=10 tells the kernel to avoid swapping unless memory pressure is high. vfs_cache_pressure keeps the page cache from being evicted too aggressively, which is useful on small RAM systems.

  4. Secure the swap file
    Swap contains RAM contents, which may include passwords. Setting chmod 600 restricts access to root. Additionally, enable swapaccount in the kernel if you need accurate accounting for containers.


Using systemd-swap for Dynamic Management

systemd-swap automatically creates and removes swap files based on RAM usage. It’s lightweight and respects security defaults.

sudo apt install systemd-swap

Configuration lives in /etc/systemd/swap.conf. A minimal config:

# /etc/systemd/swap.conf
# Create swap only if RAM < 1GB
minram=1G
# Max swap size 512M
maxswap=512M
# Use swapfile instead of swap partition
swapfile=yes

systemd-swap runs as a service, so you can monitor it:

systemctl status systemd-swap
journalctl -u systemd-swap

If you prefer a swap partition, set swapfile=no and create a dedicated partition. The partition should be marked with the swap type and noauto in /etc/fstab to avoid accidental mounting.


Trade‑offs: Swap vs. RAM

Approach Pros Cons
No swap No disk usage, no potential data leakage System may OOM if RAM exhausted
Small swap file Keeps OOM protection, minimal disk use Still a risk if swap is compromised
Swap partition Easier to wipe, can be encrypted Requires extra partition, harder to resize
systemd-swap Dynamic, minimal configuration Adds a daemon, slight overhead

On a VPS with 2 GB RAM, the default kernel swappiness is 60, which is aggressive. Reducing it to 10 or 5 can prevent swap usage unless absolutely necessary. However, if your workloads involve memory‑intensive containers, a small swap can act as a safety net.


Security Considerations

  1. Encryption
    Swap can expose sensitive data if the disk is compromised. On a VPS, you can encrypt the swap file with cryptsetup:

    sudo cryptsetup luksFormat /swapfile
    sudo cryptsetup open /swapfile cryptswap
    sudo mkswap /dev/mapper/cryptswap
    sudo swapon /dev/mapper/cryptswap
    

    Add to /etc/crypttab and /etc/fstab accordingly. This adds a small performance hit but protects data at rest.

  2. Access Control
    The 600 permission is the minimum. Avoid chmod 666 or leaving the file world‑readable.

  3. Audit
    Regularly run swapon --show and df -h to ensure no orphaned swap files appear. A cron job can alert you:

    0 3 * * * root /usr/local/bin/check_swap.sh
    

    Where check_swap.sh checks for /swapfile existence and logs to /var/log/swapcheck.log.

  4. Kernel Hardening
    The kernel’s CONFIG_SWAP is usually enabled. If you’re building a custom kernel for a highly secure environment, you can disable it, but then you must ensure all workloads fit in RAM.


Troubleshooting Common Issues

Symptom Likely Cause Fix
swapon: /swapfile: No such file or directory Swap file deleted but /etc/fstab still references it Edit /etc/fstab to remove the line
Swap file appears in df but not in swapon --show File exists but not activated Run sudo swapon /swapfile or add to /etc/fstab
System OOM after a memory spike Swap size too small or swappiness too low Increase swap size or adjust swappiness
Swap file not encrypted cryptsetup not configured Follow encryption steps above

Automating Cleanup with a One‑liner

If you want a quick cleanup script that removes any orphaned swap file and ensures /etc/fstab is clean:

#!/usr/bin/env bash
set -euo pipefail

SWAPFILE="/swapfile"

# Remove from fstab
sudo sed -i "/$SWAPFILE/d" /etc/fstab

# If file exists, delete it
[ -f "$SWAPFILE" ] && sudo rm -f "$SWAPFILE"

echo "Orphaned swap cleaned up."

Save as /usr/local/bin/cleanup-swap.sh, make it executable, and run as needed.


When to Avoid Swap Altogether

If your VPS is dedicated to a single, memory‑bounded service (e.g., a small web server or a stateless API), you can disable swap entirely:

sudo swapoff -a
sudo sed -i '/swap/d' /etc/fstab

This eliminates the risk of swap data leakage and frees the disk space for other uses. Just monitor RAM usage; if you hit 90%+ usage, consider adding a small swap file or upgrading the instance.


Final Checklist

  • Verify no swap is active: swapon --show
  • Ensure /etc/fstab has no orphan entries
  • Delete any unused swap files or partitions
  • Create a minimal swap file if needed
  • Set vm.swappiness to a low value
  • Encrypt swap if the VPS is exposed to untrusted storage
  • Add a cron job to audit swap status

Keeping swap tidy on a small VPS is a small task that saves disk space and reduces attack surface. With the steps above, you’ll avoid the common pitfall of orphaned swap files and maintain a lean, secure system.


See also