BRKH Blog

Cheap Deployment: Cloudflare Workers, a Podman VPS, and Cloudflare Tunnel

Running a full-stack application usually forces a choice between two options that both feel excessive. The first is a managed platform: frontend hosting, managed database, load balancer, and a bill that grows with every component added. The second is a single VPS — which usually ends with an afternoon spent installing Nginx, Certbot, and firewall rules before a line of application code gets written.

There is a third path, and it is much quieter. The frontend and the proxy layer run on the Cloudflare Workers Free plan, while compute and database run on one cheap VPS using rootless Podman. The VPS opens no HTTP/HTTPS ports at all: Cloudflare Tunnel connects it to the internet through an outbound connection from inside the machine.

The result is an application with four layers, each with one clear job, and no load balancer, no managed database, and no Certbot.

Version note

This article was last updated on 1 November 2026. Cloudflare's limits and prices change over time; check the official pages in References before making a production decision.

Architecture

 Users (browser / mobile)
        │  HTTPS
        ▼
 ┌──────────────────────────────────────────────┐
 │ Cloudflare Edge                              │
 │                                              │
 │  Worker  (app.example.com)                   │
 │   ├─ /*       → Static Assets (frontend)     │
 │   └─ /api/*   → fetch("https://origin.example.com")
 │                                              │
 │  Origin hostname (origin.example.com)        │
 │   └─ served by Cloudflare Tunnel             │
 └──────────────────────────┬───────────────────┘
                            │  OUTBOUND connection from the VPS
                            │  (no inbound ports open)
 ┌──────────────────────────▼───────────────────┐
 │ VPS  (Linux + rootless Podman)               │
 │                                              │
 │  Podman network: appnet                      │
 │   ├─ cloudflared ──► http://app:3000         │
 │   ├─ app (API/backend) ──► postgres:5432     │
 │   └─ postgres  (volume: pgdata)              │
 └──────────────────────────────────────────────┘

Each component's role:

ComponentRole
Cloudflare WorkerThe public entry point. Serves the frontend as static assets and forwards /api/* requests to the backend. It can also add a shared secret header, caching, and light validation.
Cloudflare Tunnel (cloudflared)Opens an outbound connection from the VPS to Cloudflare, then routes traffic for the origin hostname to the application container.
Podman (rootless)Runs containers without a root daemon. Quadlet integrates them with systemd, so they start on boot and restart on crash.
Application containerThe backend/API — Node.js, Go, Python, Rust, whatever you use.
Database containerPostgreSQL here. MariaDB, or SQLite + Litestream, work just as well.

Why this pattern is cheap

  • No load balancer, NAT gateway, or managed database. All compute and data live on one machine you pay for monthly.
  • Requests to static assets are free and unlimited. Only dynamic requests (/api/*) consume the daily Worker quota.
  • The Tunnel is free and removes the need to open ports 80/443, shrinking the attack surface dramatically.
  • TLS is handled by Cloudflare. No Certbot, no reverse proxy on the VPS.
  • Rootless Podman + Quadlet gives systemd-style service management without adding an orchestration tool.

Cost estimate

ItemCost (approximate)Notes
Cloudflare Workers (Free)$0100,000 requests/day
Cloudflare Tunnel & Zero Trust (Free)$0
VPS, 1–2 vCPU, 2–4 GB RAM~US$4–10 / monthDepends on provider and region
Domain~US$10–15 / yearRequired for the origin hostname
Off-site backup (Cloudflare R2)$0 while within the free tierCheck current R2 pricing
Total≈ US$5–11 / month

Two things that are easy to miss:

  • The VPS figure is a rough estimate. Compare a few providers, including local ones if most of your users are in Indonesia.
  • A domain is required. The tunnel hostname, such as origin.example.com, must live in a DNS zone you manage on Cloudflare. A *.workers.dev subdomain is enough for the Worker, but not for the tunnel hostname.

Free plan limits you must understand

LimitValue (Workers Free)
Requests per day100,000, reset at midnight UTC
CPU time per request10 ms (network/fetch() waiting time is not counted)
Memory per isolate128 MB
Subrequests per request50
Request body sizeFollows the account plan (Free: 100 MB)
Static asset files20,000 per Worker version, up to 25 MiB each
Requests to static assetsFree and unlimited

The practical consequences:

  1. 100,000 requests/day ≈ 1.15 requests/second averaged across the day. Enough for internal tools, MVPs, side projects, and small-to-medium sites.
  2. Serve the frontend as static assets, not through Worker code. Pages, JS, CSS, and images do not consume quota; only /api/* wakes the Worker.
  3. 10 ms of CPU is plenty for a simple proxy. Avoid large JSON parsing, heavy cryptography, or templating inside the Worker. Move that work to the backend.
  4. When the quota runs out, behaviour depends on the path. A normal Worker invocation gets error 1027. With run_worker_first, matching requests get a 429 and do not fall back to static assets — so static pages keep loading while the API stops. Watch usage in the Cloudflare dashboard.
  5. Every layer is a single point of failure. One VPS means downtime on reboot, during maintenance, or when the provider has a bad day. Accept that trade-off deliberately, or plan for HA later.

Prerequisites

  • A free Cloudflare account with Zero Trust access (the Free plan is enough for Tunnel).
  • A domain whose nameservers already point at Cloudflare.
  • A VPS with a modern Podman:
    • Ubuntu 24.04 LTS, Debian 13, Fedora, or AlmaLinux/Rocky 9.
  • Node.js LTS locally for Wrangler.
  • A frontend repository, a backend image in a container registry (GHCR or Docker Hub), and access to that registry.
  • A VPS region close to your users. For Indonesia, Singapore or a local region usually gives the best latency.

Debian 12

Debian 12 ships Podman 4.3, which is too old for the Quadlet features used here. Some keys, such as Secret=, also require a newer release. If you must stay on Debian 12, install a newer Podman from upstream.

A reasonable minimum: 1 vCPU, 2 GB RAM, 25+ GB SSD for a small app plus PostgreSQL.

Step 1: prepare and harden the VPS

Log in as root for the first time, then do the basic hardening.

Update the system

apt update && apt upgrade -y        # Debian/Ubuntu
# dnf upgrade -y                    # Fedora/RHEL family

Create a non-root deployment user

adduser deploy
usermod -aG sudo deploy             # Debian/Ubuntu (RHEL family: wheel)

Copy your SSH public key from your local machine:

ssh-copy-id deploy@VPS_IP

Disable password and root SSH login

Edit /etc/ssh/sshd_config or a file under /etc/ssh/sshd_config.d/:

PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
systemctl restart ssh      # or: systemctl restart sshd

TIP

Test the new login in another terminal before closing the old session, so you do not lock yourself out of your own server.

Firewall: only SSH needs to be open

Because of the Tunnel, ports 80/443 never need to be opened.

ufw default deny incoming
ufw default allow outgoing
ufw allow OpenSSH
ufw enable

Worth adding:

apt install -y unattended-upgrades fail2ban
dpkg-reconfigure -plow unattended-upgrades

Swap on a 2 GB VPS

fallocate -l 2G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
echo '/swapfile none swap sw 0 0' >> /etc/fstab

Reduce unnecessary swapping so the database does not slow down for no reason:

echo 'vm.swappiness=10' > /etc/sysctl.d/99-swappiness.conf
sysctl --system

Time zone

timedatectl set-timezone Asia/Jakarta     # or Asia/Makassar, Asia/Jayapura, UTC

Store timestamps in the database as UTC and convert only when displaying them.

Step 2: rootless Podman

Log in as deploy and install:

sudo apt install -y podman uidmap slirp4netns passt aardvark-dns netavark
podman --version

netavark and aardvark-dns are what let containers on the same network find each other by container name — postgres and app, for example.

Make sure subuid/subgid ranges exist:

grep deploy /etc/subuid /etc/subgid

If they are empty:

sudo usermod --add-subuids 100000-165535 --add-subgids 100000-165535 deploy

Enable linger. This is the step people forget most often: without linger, rootless containers stop when the SSH session closes and do not start on boot.

sudo loginctl enable-linger deploy

Test:

podman run --rm docker.io/library/hello-world

Step 3: create the Cloudflare Tunnel

There are two modes: remotely-managed through the dashboard with a token, and locally-managed with a config.yml. This guide uses the first, because it is simplest for containers.

Create the tunnel

  1. Open Zero Trust dashboard → Networks → Tunnels (menu names vary slightly between dashboard versions).
  2. Click Create a tunnel and choose Cloudflared.
  3. Name it, for example vps-sg-01.
  4. On the connector installation step, choose Docker. From the command shown, copy only the token value after --token. You will not run that command directly; the token becomes a Podman secret.

Add a public hostname

FieldValue
Subdomain / Domainorigin / example.com
Service typeHTTP
URLapp:3000

Traffic to origin.example.com is forwarded by cloudflared to the container named app on port 3000 in the same Podman network. Creating this hostname automatically creates a proxied CNAME record.

Keep hostnames separate

Use one hostname for the origin (origin.example.com) and another for the Worker (app.example.com). Never create a Worker route that also covers the origin hostname — the Worker will call itself and loop.

Step 4: database, application, and cloudflared with Quadlet

Quadlet lets you describe containers declaratively in .container, .network, and .volume files, which Podman translates into systemd units. This is the recommended approach over podman generate systemd.

Directory layout

mkdir -p ~/.config/containers/systemd
~/.config/containers/systemd/
├── appnet.network
├── pgdata.volume
├── postgres.container
├── app.container
└── cloudflared.container

Store credentials as Podman secrets

Never put passwords in Quadlet files or committed environment variables.

# database password
printf '%s' 'YOUR_STRONG_PASSWORD' | podman secret create pg_password -

# connection string for the application (host = database container name)
printf '%s' 'postgres://appuser:YOUR_DB_PASSWORD@postgres:5432/appdb' \
  | podman secret create database_url -

# tunnel token from the previous step
printf '%s' 'YOUR_TUNNEL_TOKEN' | podman secret create cf_tunnel_token -

# shared secret proving a request came from the Worker
openssl rand -hex 32 | tr -d '\n' | podman secret create origin_secret -

podman secret ls

If the password contains special characters (@, :, /, #), URL-encode the value in database_url or pick a long alphanumeric password.

Network and volume

~/.config/containers/systemd/appnet.network

[Network]
NetworkName=appnet

~/.config/containers/systemd/pgdata.volume

[Volume]
VolumeName=pgdata

PostgreSQL

~/.config/containers/systemd/postgres.container

[Unit]
Description=PostgreSQL database
After=network-online.target

[Container]
Image=docker.io/library/postgres:17
ContainerName=postgres
Network=appnet.network
Volume=pgdata.volume:/var/lib/postgresql/data

Environment=POSTGRES_DB=appdb
Environment=POSTGRES_USER=appuser
Secret=pg_password,type=env,target=POSTGRES_PASSWORD

# Light tuning for a 2 GB VPS
Exec=postgres -c shared_buffers=256MB -c effective_cache_size=768MB -c max_connections=50 -c work_mem=8MB

# Cap memory so the database cannot take the whole VPS
PodmanArgs=--memory=1g

HealthCmd=pg_isready -U appuser -d appdb
HealthInterval=30s
HealthRetries=3

# NO PublishPort: the database is reachable only from appnet.

[Service]
Restart=always
TimeoutStartSec=120

[Install]
WantedBy=default.target

Important points:

  • Pin the major version (postgres:17). Do not use latest for a database: a major PostgreSQL upgrade needs a data migration, not a tag change.
  • Do not add PublishPort=5432. The database never needs to be exposed to the host or the internet.
  • Adjust the tuning numbers to your VPS RAM. A common starting point is shared_buffers at about 25% of the RAM allocated to the database.

Application backend

~/.config/containers/systemd/app.container

[Unit]
Description=Backend application
Requires=postgres.service
After=postgres.service

[Container]
Image=ghcr.io/USERNAME/REPO:v1.0.0
ContainerName=app
Network=appnet.network

Environment=NODE_ENV=production
Environment=PORT=3000
Secret=database_url,type=env,target=DATABASE_URL
Secret=origin_secret,type=env,target=ORIGIN_SECRET

PodmanArgs=--memory=512m

HealthCmd=wget -qO- http://127.0.0.1:3000/healthz || exit 1
HealthInterval=30s
HealthRetries=3

# Optional: auto-update from the registry (see CI/CD)
# AutoUpdate=registry

[Service]
Restart=always

[Install]
WantedBy=default.target

Notes:

  • The application must listen on 0.0.0.0:3000, not 127.0.0.1, so cloudflared can reach it.
  • The application should retry the database connection at startup. After= only orders the start; it does not mean the database is ready to accept connections.
  • If the image is private, log in first: podman login ghcr.io.
  • Make sure the image contains wget or curl if you use the HealthCmd above.

cloudflared

~/.config/containers/systemd/cloudflared.container

[Unit]
Description=Cloudflare Tunnel connector
Requires=app.service
After=app.service

[Container]
Image=docker.io/cloudflare/cloudflared:2026.10.7
ContainerName=cloudflared
Network=appnet.network
Secret=cf_tunnel_token,type=env,target=TUNNEL_TOKEN
Exec=tunnel --no-autoupdate run

[Service]
Restart=always
RestartSec=5

[Install]
WantedBy=default.target

Pin the current release tag when you do this — 2026.10.7 was current when this article was updated. Pinning makes rollback easy, but do not leave it stale for too long: cloudflared must keep up with changes on Cloudflare's side.

If the logs warn about UDP/QUIC buffers, raise them:

sudo sysctl -w net.core.rmem_max=7500000 net.core.wmem_max=7500000

Make it permanent under /etc/sysctl.d/, or force HTTP/2 with Exec=tunnel --no-autoupdate --protocol http2 run.

Enable and start

systemctl --user daemon-reload

systemctl --user start postgres.service app.service cloudflared.service

systemctl --user status postgres app cloudflared
podman ps

Logs:

journalctl --user -u cloudflared -f
journalctl --user -u app -f
journalctl --user -u postgres -f

If a Quadlet file has a syntax error, check it with:

/usr/lib/podman/quadlet -dryrun -user
# the binary may be at /usr/libexec/podman/quadlet depending on the distro

In the Cloudflare dashboard, the tunnel should now show as Healthy. Test from outside:

curl -i https://origin.example.com/healthz

Before the origin is locked down, this request is still served. After the lockdown, requests without the secret header are rejected — which is the point.

Alternative: podman-compose

If you prefer a compose.yaml, podman-compose or podman compose will work. The catch is weaker systemd integration: start-on-boot, dependency ordering, and logs all become more manual. For production on a single VPS, Quadlet is the better choice.

Rootless operational notes

  • Volumes and permissions. Named volumes are handled by Podman, so file ownership inside the container is usually correct without manual steps. For bind mounts, mind the UID mapping and use :U or podman unshare chown.
  • Ports below 1024 cannot be bound by rootless containers by default. That is irrelevant here because nothing is published.
  • Disk. Clean old images periodically with podman image prune -a, after confirming the images in use are running.

Step 5: a Worker as frontend and proxy

The pattern: the Worker serves the frontend as static assets and only runs code for /api/*. That way the daily quota is spent only on API requests.

Initialize the project

npm create cloudflare@latest my-app
cd my-app
npm install

Example structure:

my-app/
├── dist/                 # frontend build output (Vite/React/Vue/Svelte, etc.)
├── src/
│   └── index.ts          # Worker code (proxy)
├── wrangler.jsonc
└── package.json

Using Bun

With Bun, bun create cloudflare@latest my-app and bunx wrangler deploy do the same thing. The npm commands below are kept to match the official Wrangler documentation.

wrangler.jsonc

{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "my-app",
  "main": "src/index.ts",
  // Set this to the date you work on the project
  "compatibility_date": "2026-11-01",

  "assets": {
    "directory": "./dist",
    "binding": "ASSETS",
    // For an SPA (React Router, Vue Router, etc.): fall back to index.html
    "not_found_handling": "single-page-application",
    // Only these paths run Worker code; everything else is served as an asset
    "run_worker_first": ["/api/*"]
  },

  "vars": {
    "ORIGIN_URL": "https://origin.example.com"
  },

  // Custom domain for the Worker (the zone must be in the same account)
  "routes": [
    { "pattern": "app.example.com", "custom_domain": true }
  ],

  "observability": { "enabled": true }
}

Never put secrets in vars:

npx wrangler secret put ORIGIN_SECRET
# paste the same value as the "origin_secret" podman secret on the VPS

podman secret inspect --showsecret origin_secret shows the value on the VPS if you need to copy it into a password manager.

src/index.ts: proxy to the backend

export interface Env {
  ASSETS: Fetcher;
  ORIGIN_URL: string;      // e.g. https://origin.example.com
  ORIGIN_SECRET: string;   // Wrangler secret
}

// Headers that must not be forwarded as-is
const HOP_BY_HOP = [
  "connection",
  "keep-alive",
  "proxy-authenticate",
  "proxy-authorization",
  "te",
  "trailer",
  "transfer-encoding",
  "upgrade",
];

async function proxyToOrigin(request: Request, env: Env): Promise<Response> {
  const incoming = new URL(request.url);
  const target = new URL(incoming.pathname + incoming.search, env.ORIGIN_URL);

  // Copy method, body, and headers from the original request
  const upstream = new Request(target, request);

  // Strip hop-by-hop headers, except the ones WebSocket needs
  const isWebSocket =
    request.headers.get("upgrade")?.toLowerCase() === "websocket";
  for (const h of HOP_BY_HOP) {
    if (isWebSocket && (h === "upgrade" || h === "connection")) continue;
    upstream.headers.delete(h);
  }

  // Worker -> origin authentication
  upstream.headers.set("X-Origin-Secret", env.ORIGIN_SECRET);

  // Forward the real client IP. Do not rely on CF-Connecting-IP at the
  // origin: the request comes from the Worker, not from the client.
  const clientIp = request.headers.get("cf-connecting-ip");
  if (clientIp) {
    upstream.headers.set("X-Real-Client-IP", clientIp);
    upstream.headers.set("X-Forwarded-For", clientIp);
  }
  upstream.headers.set("X-Forwarded-Host", incoming.host);
  upstream.headers.set("X-Forwarded-Proto", "https");

  try {
    const response = await fetch(upstream, { redirect: "manual" });

    const out = new Response(response.body, response);
    out.headers.set("X-Content-Type-Options", "nosniff");
    return out;
  } catch (err) {
    console.error("Origin fetch failed:", err);
    return Response.json(
      { error: "bad_gateway", message: "The backend is unreachable." },
      { status: 502 },
    );
  }
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const { pathname } = new URL(request.url);

    if (pathname.startsWith("/api/")) {
      return proxyToOrigin(request, env);
    }

    // Fallback when the Worker is invoked directly (e.g. workers.dev):
    // serve static assets
    return env.ASSETS.fetch(request);
  },
} satisfies ExportedHandler<Env>;

Design decisions worth understanding:

  • redirect: "manual" stops the Worker from following backend redirects, so the browser receives the original redirect.
  • X-Real-Client-IP must be forwarded explicitly because the request to the origin comes from the Worker. At the backend, trust this header only after X-Origin-Secret has been verified.
  • Streaming. new Response(response.body, response) forwards the body as a stream instead of buffering it into the Worker's 128 MB of memory.
  • WebSocket requests can be proxied through the same fetch(), but test under real load. A long-lived connection still counts as one request when opened.

Caching GET responses (optional)

For public endpoints that rarely change:

const response = await fetch(upstream, {
  redirect: "manual",
  cf: {
    cacheEverything: true,
    cacheTtl: 60,              // seconds
    cacheKey: target.toString(),
  },
});

Use this only for GET requests without per-user data. Never cache responses that carry cookies or Authorization unless you understand the consequences. Caching reduces backend load, but does not reduce the number of Worker invocations.

CORS

Because the frontend and API share an origin (app.example.com and app.example.com/api/*), you need no CORS at all. Session cookies are simpler too: SameSite=Lax, Secure, HttpOnly.

Build and deploy

npm run build
npx wrangler deploy

Test locally:

npx wrangler dev

After deploying, open https://app.example.com and https://app.example.com/api/healthz.

Locking down the origin

The tunnel hostname (origin.example.com) is public. Anyone who learns it can reach it directly, bypassing the Worker. The origin must therefore accept traffic only from your Worker.

Option A: shared secret header

The Worker already sends X-Origin-Secret. The backend rejects requests without a matching header. Example Express middleware:

import { timingSafeEqual } from "node:crypto";

const secret = Buffer.from(process.env.ORIGIN_SECRET ?? "");

export function requireOriginSecret(req, res, next) {
  const got = Buffer.from(req.get("x-origin-secret") ?? "");
  if (got.length !== secret.length || !timingSafeEqual(got, secret)) {
    return res.status(403).json({ error: "forbidden" });
  }
  next();
}

// app.use(requireOriginSecret);

The constant-time comparison above avoids timing attacks. Exempt the internal /healthz if it genuinely needs to be called without the header.

Option B: a WAF custom rule

Create a custom rule on your zone that blocks requests to origin.example.com when X-Origin-Secret does not match. Malicious traffic is rejected at Cloudflare's edge, before it reaches the VPS. Custom rule quotas on the Free plan are limited, so check yours.

Option C: Cloudflare Access with a service token

  1. Zero Trust → Access → create a Service Token (you get a Client ID and Client Secret).
  2. Create an Access application for origin.example.com with a Service Auth policy that allows only that token.
  3. Send these headers from the Worker:
upstream.headers.set("CF-Access-Client-Id", env.CF_ACCESS_CLIENT_ID);
upstream.headers.set("CF-Access-Client-Secret", env.CF_ACCESS_CLIENT_SECRET);

Authentication happens before traffic enters the tunnel, and tokens can be rotated without touching backend code.

Option D: Workers VPC

Workers VPC lets a Worker reach private services through Cloudflare Tunnel via a binding, with no public hostname for the origin. The flow: create a tunnel, register a VPC Service, add vpc_services to wrangler.jsonc, then call env.PRIVATE_API.fetch(...).

{
  "vpc_services": [
    { "binding": "PRIVATE_API", "service_id": "<SERVICE_ID>", "remote": true }
  ]
}

This removes the "public origin can be hit directly" risk. It is still beta, free for all Workers plans during beta, and its API may change before GA — verify against the documentation before relying on it.

Extra security checklist

  • [ ] No PublishPort on the database and application containers.
  • [ ] The VPS firewall opens only SSH.
  • [ ] SSH is key-only; root login is disabled.
  • [ ] Every credential lives in a Podman secret or a Wrangler secret, never in Git.
  • [ ] The database user has the minimum privileges, not superuser.
  • [ ] Rate limiting at Cloudflare and/or in the app for sensitive endpoints such as login.
  • [ ] Consider Cloudflare Turnstile for public forms.
  • [ ] Security headers (CSP, HSTS, X-Frame-Options) are set in the Worker or via Transform Rules.
  • [ ] The OS, Podman, and container images are updated regularly.
  • [ ] Backups have been test-restored.

Backups and database recovery

One VPS is one point of failure

Backups are not optional. Provider snapshots help, but a logical dump stored outside the VPS is far more reliable.

Backup script

/home/deploy/bin/backup-db.sh

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

BACKUP_DIR="/home/deploy/backups"
TS="$(date -u +%Y%m%d-%H%M%S)"
OUT="${BACKUP_DIR}/appdb-${TS}.sql.gz"

mkdir -p "${BACKUP_DIR}"

# Dump from the database container
podman exec postgres pg_dump -U appuser -d appdb --no-owner | gzip -9 > "${OUT}"

# Verify the file is not empty
test -s "${OUT}"

# Upload off-site (example: rclone to Cloudflare R2, remote named "r2")
rclone copy "${OUT}" r2:backup-bucket-name/appdb/

# Keep only 7 days of local backups
find "${BACKUP_DIR}" -type f -name 'appdb-*.sql.gz' -mtime +7 -delete

echo "Backup finished: ${OUT}"
chmod +x /home/deploy/bin/backup-db.sh

Schedule it with a systemd timer

~/.config/systemd/user/backup-db.service

[Unit]
Description=Database backup

[Service]
Type=oneshot
ExecStart=/home/deploy/bin/backup-db.sh

~/.config/systemd/user/backup-db.timer

[Unit]
Description=Daily database backup

[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true
RandomizedDelaySec=300

[Install]
WantedBy=timers.target
systemctl --user daemon-reload
systemctl --user enable --now backup-db.timer
systemctl --user list-timers

Restore, and practice it

# Create an empty database for a restore test
podman exec postgres createdb -U appuser appdb_restore_test

# Restore
gunzip -c appdb-20261101-030000.sql.gz | podman exec -i postgres psql -U appuser -d appdb_restore_test

# Check the contents, then remove it
podman exec postgres dropdb -U appuser appdb_restore_test

Schedule a restore drill every few months. A backup that has never been restored is not yet a backup.

Tips

  • Ping Healthchecks.io at the end of the script so you are told when backups stop running.
  • For larger databases or point-in-time recovery, look into WAL archiving (pgBackRest or WAL-G).
  • For small apps, SQLite + Litestream replicating to R2/S3 can be lighter than PostgreSQL.

CI/CD

Deploy the Worker

.github/workflows/deploy-worker.yml

name: Deploy Worker
on:
  push:
    branches: [main]
    paths: ["src/**", "frontend/**", "wrangler.jsonc", "package.json"]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 24
          cache: npm
      - run: npm ci
      - run: npm run build
      - uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}

Create a Cloudflare API Token with the narrowest permissions possible — the "Edit Cloudflare Workers" template is a reasonable starting point — and store it in GitHub Secrets.

Build and publish the backend image

name: Build Backend
on:
  push:
    tags: ["v*"]

jobs:
  image:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
    steps:
      - uses: actions/checkout@v4
      - uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - uses: docker/build-push-action@v6
        with:
          context: ./backend
          push: true
          tags: ghcr.io/${{ github.repository }}:${{ github.ref_name }}

Deploy to the VPS

The safe manual path, and the one to start with:

ssh deploy@VPS_IP
# change the image tag in ~/.config/containers/systemd/app.container, then:
systemctl --user daemon-reload
systemctl --user restart app.service
journalctl --user -u app -n 50 --no-pager

For automation, add AutoUpdate=registry to app.container and enable Podman's built-in timer.

systemctl --user enable --now podman-auto-update.timer

Auto-update is not a safe default

A moving tag (latest) can bring unexpected changes. Use fixed tags in production, or accept the risk knowingly. Never auto-update the database image without a plan — major PostgreSQL upgrades need a migration. Podman can roll back automatically when a service fails to start after an update, provided HealthCmd and Restart= are configured correctly.

Database migrations

Run migrations as a controlled step, not automatically on every restart:

podman run --rm --network appnet \
  --secret database_url,type=env,target=DATABASE_URL \
  ghcr.io/USERNAME/REPO:v1.0.0 npm run migrate

Back up before any destructive migration.

Monitoring and operations

Routine checks

systemctl --user --failed
podman ps -a
podman stats --no-stream
df -h
free -h
journalctl --user -p err --since "24 hours ago" --no-pager

What is worth watching

  • An external uptime check (UptimeRobot, Better Stack, or similar) against https://app.example.com/api/healthz.
  • The Cloudflare dashboard: Workers analytics (requests, errors, CPU time), tunnel status, and usage against the 100,000 requests/day limit.
  • Workers Logs are available on the Free plan with short retention. For longer history, ship important backend logs to an external service.
  • Healthchecks.io for scheduled jobs such as backups.
  • Avoid running a heavy monitoring stack (Prometheus + Grafana + Loki) on the same small VPS; the database needs that RAM.

Log rotation

Cap journald so the disk does not fill up:

# /etc/systemd/journald.conf.d/size.conf
[Journal]
SystemMaxUse=500M

Routine updates

  • OS: unattended-upgrades for security patches, plus scheduled reboots when the kernel is updated.
  • Podman and images: review monthly.
  • cloudflared: update regularly and watch for deprecation notices from Cloudflare.
  • After a VPS reboot, confirm every service came back on its own. Test this once with sudo reboot during setup, not while panicking.

Troubleshooting

SymptomLikely causeFix
Containers die when SSH closes / do not start on bootLinger is not enabledsudo loginctl enable-linger deploy
systemctl --user start xxx → unit not foundQuadlet syntax/location problem, or no daemon-reloadRun daemon-reload; check with quadlet -dryrun -user
Quadlet does not recognise a key (e.g. Secret=)Podman too oldUpgrade Podman (≥ 4.9 recommended) or use a newer distro
Tunnel shows Down in the dashboardWrong token, container not running, or egress blockedjournalctl --user -u cloudflared; check the token; make sure the VPS can reach the internet
502/530 from origin.example.comcloudflared cannot reach app:3000Check ContainerName=app, the port, and that the app listens on 0.0.0.0; confirm a single shared network
postgres/app does not resolveContainers on different networks, or aardvark-dns missingEnsure Network=appnet.network everywhere; install netavark and aardvark-dns
App cannot reach the DB at bootThe DB is not ready yetAdd retry/backoff; check the DB HealthCmd and After=/Requires=
Error 524The backend takes too long (Cloudflare's origin timeout is around 100 seconds)Move slow work to a background job; reply quickly and poll
Error 1027Daily Worker quota exhaustedCheck analytics; add caching; upgrade to Workers Paid
API returns 429 while static pages still loadQuota exhausted on run_worker_first pathsSame as above; static pages are intentionally still served
Worker calls itself / loopsThe Worker route covers the origin hostnameSeparate the hostnames; the Worker route must not include the origin
Worker error "Exceeded CPU time"Too much work in the Worker (10 ms limit)Move logic to the backend; keep the Worker as a proxy
The backend always sees a Cloudflare IPRequests come from the Worker, not the clientRead X-Real-Client-IP, only after verifying X-Origin-Secret
Odd redirects / HTTPS loopsWrong SSL/TLS mode or proto headerThe origin should not force HTTPS redirects; read X-Forwarded-Proto
permission denied on a volumeRootless UID mappingUse a named volume, or :U on bind mounts, or podman unshare chown
Disk fullLogs, old images, or backups piling uppodman system df, podman image prune, cap journald, rotate backups

Diagnostic commands that often save the day:

podman logs -f cloudflared
podman network inspect appnet
podman exec -it app sh -c 'getent hosts postgres'
podman exec -it postgres psql -U appuser -d appdb -c '\conninfo'
curl -sS -H "X-Origin-Secret: $(podman secret inspect --showsecret origin_secret --format '{{.SecretData}}')" \
  https://origin.example.com/healthz

When to upgrade

SignalAction
Approaching 100,000 API requests/dayAdd caching, or move to Workers Paid (from $5/month with a much larger allowance)
10 ms CPU is regularly exceededWorkers Paid, or move the logic to the backend
VPS RAM/CPU is saturatedResize the VPS
Downtime is unacceptableReplicate the database, add a second VPS, and run a second tunnel connector on the same tunnel
Data becomes criticalManaged database, or PostgreSQL with replicas + WAL archiving
You need a global footprintConsider D1, Durable Objects, or Hyperdrive as appropriate

Worth considering as alternatives:

  • Cloudflare Pages + Pages Functions — a similar experience, and its dynamic functions are still bound by Workers Free limits.
  • Caddy/Nginx + Let's Encrypt directly on the VPS — simpler in concept, but you must open ports 80/443 and manage TLS yourself.
  • D1 / R2 / Hyperdrive — to move part of the data onto Cloudflare so not everything depends on one VPS.
  • Tailscale or Cloudflare Access — for admin access to SSH or internal dashboards without opening ports.

Policy note

Cloudflare's terms of service restrict what content may pass through the CDN/proxy on certain plans, for example serving large volumes of non-HTML media. If your application serves video or large files, read the Terms of Service and consider R2 or a service built for large files.

Go-live checklist

VPS and Podman

  • [ ] Non-root user, key-only SSH, root login disabled
  • [ ] Firewall enabled, only SSH open
  • [ ] Swap and time zone configured
  • [ ] Podman ≥ 4.9, linger enabled
  • [ ] Secrets pg_password, database_url, cf_tunnel_token, origin_secret created

Containers

  • [ ] postgres, app, cloudflared running and healthy
  • [ ] No PublishPort for the database or the application
  • [ ] Image versions pinned
  • [ ] Reboot test: every service comes back on its own

Cloudflare

  • [ ] Tunnel Healthy, public hostname pointing at app:3000
  • [ ] Origin locked down (secret header, WAF, Access, or VPC)
  • [ ] Worker deployed, route/custom domain correct
  • [ ] ORIGIN_SECRET stored as a Wrangler secret
  • [ ] The origin hostname is not covered by the Worker route

Operations

  • [ ] Daily backups running, stored off-site, and restore-tested
  • [ ] Uptime monitor active
  • [ ] journald limits configured
  • [ ] An upgrade plan ready before approaching the Free plan limits

Closing

The appeal of this pattern is not how much it can do, but how little it asks you to maintain. No load balancer to configure, no certificate to renew, no database port open to the internet, and no bill that grows because someone forgot to turn a component off. Four layers, each with one job.

The price is equally clear. You hold the pager: one VPS is one point of failure, and a backup only counts once its restore has been tested. A quota of 100,000 requests/day is enough for many projects, but not all of them. Knowing that limit up front is far more comfortable than learning it from an error 1027 in the middle of the day.

For internal tools, MVPs, or a serious side project, this combination is hard to beat: it costs roughly one VPS, and the whole system is small enough to understand in an afternoon.

References

Cloudflare Workers

Cloudflare Tunnel and Zero Trust

Podman

Other


Credits: this article was generated by the AI model DeepSeek V4.1 Flash running in the OpenCode harness.

Contents