PortGate

Blueprints · Server Hardening

Beginner 10 min · Linux

Swapfile and OOM protection for a small VPS

Creates a 2 GB swapfile with mode 600 when one is missing, and sets swappiness to 10 and vfs_cache_pressure to 50. Running it again does not recreate the file.

Baked-in protections

Step 1 · bash

Create swap and sysctl

/root/portgate-blueprints/swapfile.sh

fallocate is used when it exists. Otherwise the file is filled with dd. swapon failure is reported and does not remove the file.

#!/bin/sh
set -eu
if [ ! -f /swapfile ]; then
  if command -v fallocate >/dev/null 2>&1; then
    fallocate -l 2G /swapfile
  else
    dd if=/dev/zero of=/swapfile bs=1M count=2048
  fi
fi
chmod 600 /swapfile
if ! blkid /swapfile 2>/dev/null | grep -q 'TYPE="swap"'; then
  mkswap /swapfile
fi
swapon /swapfile || echo "swapon failed. /swapfile was left in place."
grep -q '/swapfile' /etc/fstab || printf '%s\n' '/swapfile none swap sw 0 0' >> /etc/fstab
printf '%s\n' 'vm.swappiness = 10' 'vm.vfs_cache_pressure = 50' > /etc/sysctl.d/99-portgate-swap.conf
sysctl -w vm.swappiness=10
sysctl -w vm.vfs_cache_pressure=50

Step 2 · conf

Sysctl drop-in

/etc/sysctl.d/99-portgate-swap.conf

The script writes this file as well. It is here so you can copy it onto a host that already has the swapfile.

vm.swappiness = 10
vm.vfs_cache_pressure = 50