404human Experience Projects Writing Build logs Learning Books Progress
Rust · Zola
zsh · 404human@dev:~ Tab complete · ↑↓ history · type help

Linux server hardening & zero-downtime deploys on a single VPS

Practical VPS security and Linux server hardening with systemd, Caddy, Cloudflare Authenticated Origin Pulls, systemd timers, and measured zero-downtime deploys.

Published
Read time
5 min read
Kind
guide
Topics

You do not need Kubernetes to run a hardened, zero-downtime production backend. You do need more than renting a $12 Linux VPS, installing a binary as root, and walking away.

Most single-VPS breaches and deploy outages come from the same five mistakes: password SSH left open, backend ports accidentally reachable bypassing Cloudflare, services running as root with write access to the whole disk, silent cron backup failures, and restarts that drop live HTTP/SSE connections with 502 Bad Gateway.

Here is the exact Linux server hardening + zero-downtime deployment blueprint we run for real production services behind Caddy and Cloudflare—including the measured deploy numbers we saw before and after fixing graceful draining.

Layer 1: SSH, firewall, and origin lock-down (VPS security baseline)

Start with the network perimeter before deploying any application code:

1. Lock down SSH (/etc/ssh/sshd_config.d/99-hardening.conf)

Create a non-root admin user with sudo, copy your Ed25519 SSH key, verify you can log in with it in a second terminal before closing your current one, and lock SSH down:

PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
AllowUsers deploy

Reload with sudo sshd -t && sudo systemctl reload ssh.

2. Minimal firewall (ufw) + automatic security patches

Only expose SSH (ideally restricted to your VPN/Tailscale IP) and 80/443 for your reverse proxy. Never expose 5432, 6379, or your app’s 8080 port directly:

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp   # Better: allow only from Tailscale / WireGuard interface
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
sudo apt install -y unattended-upgrades

3. Prevent Cloudflare bypass (Authenticated Origin Pulls)

If you proxy your VPS through Cloudflare, anyone who discovers your VPS’s raw IPv4 address can still send requests straight to https://<vps-ip>—bypassing Cloudflare WAF and rate limits, and forging Cf-Connecting-Ip headers!

In Caddy, enable Cloudflare Authenticated Origin Pulls (mTLS) so Caddy rejects any TLS connection to port 443 that does not present Cloudflare’s client certificate, and only trust Cf-Connecting-Ip from verified proxy CIDRs (see why every rate limiter behind Caddy saw 127.0.0.1).

Layer 2: Hardened systemd service units

Instead of running your app inside tmux, pm2, or as root, give every backend its own unprivileged system user and a sandboxed systemd unit (/etc/systemd/system/myapp.service):

[Unit]
Description=My Production API
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=myapp
Group=myapp
WorkingDirectory=/srv/myapp
EnvironmentFile=/etc/myapp/env
ExecStart=/srv/myapp/current/myapp-server

# Graceful shutdown budget
KillSignal=SIGTERM
TimeoutStopSec=25s
Restart=on-failure
RestartSec=2s

# Kernel & filesystem hardening
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/var/lib/myapp
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
RestrictSUIDSGID=true
LockPersonality=true
CapabilityBoundingSet=
AmbientCapabilities=
MemoryMax=1G
TasksMax=512

[Install]
WantedBy=multi-user.target

Check your service’s security posture directly with systemd’s built-in auditor:

systemd-analyze security myapp.service

That single unit achieves near-container isolation with zero Docker daemon overhead and zero iptables firewall surprises. Make sure /etc/myapp/env is chmod 600 owned by root:myapp (or chmod 640 with group myapp) so no other local user can read secrets.

Layer 3: systemd timers instead of cron for backups & maintenance

Classic cron silently drops stdout, runs with a stripped PATH, and gives you no clean visibility when a nightly database backup breaks for three weeks.

Use a paired systemd service + timer instead (e.g., /etc/systemd/system/myapp-backup.service and myapp-backup.timer):

# /etc/systemd/system/myapp-backup.timer
[Unit]
Description=Nightly encrypted database backup

[Timer]
OnCalendar=*-*-* 03:15:00 UTC
RandomizedDelaySec=10m
Persistent=true

[Install]
WantedBy=timers.target

Why this wins operationally:

  • Persistent=true runs a missed backup automatically if the VPS was rebooting at 03:15.
  • Every run’s stdout, stderr, exit code, and duration are indexed in journalctl -u myapp-backup.service.
  • You can inspect every scheduled job and its last exit state in one command: systemctl list-timers --all.

Layer 4: True zero-downtime deploys on a single VPS

On a single VPS, a naive systemctl restart myapp stops the old process before the new process binds the port—leaving a 1–15 second window where Caddy returns 502 Bad Gateway.

Two things eliminate that window completely:

1. Blue/Green local ports behind Caddy (true 0 ms cutover)

Run two template units ([email protected] and [email protected]). During a deploy:

1. Live traffic hits :8081 (blue)
2. Upload new binary atomically (install -m 755 new /srv/myapp/releases/<sha>/app)
3. Start myapp@8082 (green) and poll http://127.0.0.1:8082/readyz until 200 OK
4. Reload Caddy (zero dropped connections) to point upstream to 127.0.0.1:8082
5. Send SIGTERM to myapp@8081 — old in-flight requests finish cleanly, then exit

If /readyz on :8082 fails (bad migration, missing env var, panic on boot), live traffic on :8081 is untouched—rollback is literally doing nothing.

2. Cancel long-lived streams (SSE / WebSockets) the moment draining begins

Even with graceful shutdown, one subtle trap ruins deploys: an open Server-Sent Events (/events) stream counts as an in-flight HTTP request.

When we first deployed Colophon CMS with an editor tab holding an open SSE stream, axum::serve waited out the entire 25-second shutdown deadline before letting the new binary take over. Cancelling the SSE CancellationToken the moment SIGTERM flipped /readyz to 503 fixed it completely—measured directly against the live production server (full post-mortem):

Production deploy drill (with open SSE stream)Failed HTTP probesFailure windowTotal switch time
Before fix (SSE held shutdown until deadline)3 / 40712.9 s29 s
After fix (SSE cancelled immediately on drain)0 / 4110 s10 s

Combine atomic blue/green port switching with immediate stream draining, and deploys become genuinely boring—even with active users streaming live updates.

Verification checklist (run after every server setup)

  1. sudo sshd -T | grep -E 'permitrootlogin|passwordauthentication' → both no.
  2. sudo ss -tulpn → confirm only 22, 80, and 443 listen on 0.0.0.0/[::]; app & DB ports listen only on 127.0.0.1.
  3. curl -sk https://<raw-vps-ip>/ → fails TLS handshake (Cloudflare Authenticated Origin Pulls enforced).
  4. systemd-analyze security myapp.service → confirm low exposure score, non-root User, ProtectSystem=strict.
  5. Run a live deploy while a probe script curls /healthz every 200 ms → verify 0 non-200 responses.

Frequently asked questions

Is a single Linux VPS secure enough for production SaaS? Yes—when hardened properly. A boring Ubuntu LTS droplet with SSH key-only login, UFW firewall, Cloudflare Authenticated Origin Pulls, locked-down systemd service units, automated security updates, and off-box backups has a smaller attack surface than many misconfigured multi-cluster Kubernetes setups.

How do you achieve zero-downtime deployments on a single VPS without Kubernetes? Pair an atomic binary/release swap with graceful shutdown and readiness draining—or run two local backend ports (blue/green) behind Caddy with health checks so Caddy only switches traffic after the new binary passes /readyz and old connections drain cleanly.

Why use systemd timers instead of cron on Linux servers? systemd timers log every run automatically to journald, support randomized delays and missed-run catch-up (Persistent=true), enforce per-job memory/CPU limits and sandboxing, and never silently swallow exit codes or environment variables the way classic cron jobs often do.

Related reading