Bare-Metal k3s Multi-App Architecture: Migrating Cloud Run & Databases with Full SRE DR

Architecture Brief: Consolidate Cloud Run apps, pgvector PostgreSQL, Redis, Prometheus, Loki, and encrypted Cloudflare R2 backups on bare-metal k3s.

Multi-App Consolidation on Bare-Metal k3s, Cloudflare Free & Caddy SNI

When teams hire a Cloud Engineer or GCP Professional Cloud Architect, cloud bills often climb fastest not from compute traffic spikes, but from baseline SaaS minimums across managed Postgres instances, Redis caches, separate serverless NAT/LB tiers, and always-warm containers. Consolidating three production workloads onto a single hardened 16 vCPU / 62 GiB Ubuntu bare-metal node running lightweight k3s reduced cluster runtime usage for all application and SRE telemetry pods to 20 running pods in roughly 1.85 GiB of RAM.

Instead of forcing every workload into the same persistence model, the cluster separates stateful services from stateless hybrid applications by namespace:

app.example.com {
    tls /etc/caddy/certs/origin.crt /etc/caddy/certs/origin.key
    encode zstd gzip

    handle /_next/static/* {
        reverse_proxy 127.0.0.1:30082 {
            @ok status 200
            handle_response @ok {
                header {
                    defer
                    Cache-Control "public, max-age=31536000, immutable"
                }
                copy_response
            }
        }
    }

    reverse_proxy 127.0.0.1:30082
}

Zero-Downtime Rollouts, preStop Drains & Immutable SHA Tagging

Single-node Kubernetes deployments often suffer transient 502 errors during rolling updates because Kubernetes removes a terminating pod from EndpointSlice asynchronously while SIGTERM arrives immediately inside the container. Adding a 5-second preStop lifecycle hook lets kube-proxy iptables rules flush before the HTTP server stops accepting connections, while maxUnavailable: 0 and maxSurge: 1 ensure a replacement pod passes dedicated readiness probes before any old pod begins draining.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: next-app
  namespace: app-hub
spec:
  replicas: 2
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 0
      maxSurge: 1
  template:
    spec:
      terminationGracePeriodSeconds: 30
      securityContext:
        runAsNonRoot: true
        runAsUser: 1001
        fsGroup: 1001
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: web
          image: 127.0.0.1:5000/app-hub:latest
          lifecycle:
            preStop:
              exec:
                command: ["sh", "-c", "sleep 5"]
          startupProbe:
            httpGet:
              path: /api/health
              port: http
            failureThreshold: 12
            periodSeconds: 5
          readinessProbe:
            httpGet:
              path: /api/health
              port: http
            periodSeconds: 10

Equally important is keeping deployment scripts safe across live updates. Rather than blindly running kubectl apply -f k8s/web.yaml (whose bootstrap manifest references :latest), CI builds into a loopback-only container registry at 127.0.0.1:5000/<app>:<short_sha> and applies a strategic merge patch with kubernetes.io/change-cause so rollouts are traceable and kubectl rollout undo restores cached SHA ReplicaSets in seconds. When tuning CPU/memory quotas on a live deployment, kubectl set resources preserves the pinned SHA tag cleanly.

Hybrid Kubernetes + Managed GCP Without a Metadata Server

Migrating services off Cloud Run onto bare-metal Kubernetes breaks any library or fetch call that assumes the Compute Engine metadata server at 169.254.169.254 or metadata.google.internal is reachable. Every token request across Vertex AI and Discovery Engine services was refactored through a single helper, resolveGcpAccessToken(), backed by Application Default Credentials (ADC) via google-auth-library while preserving unit-test mock injection.

import { GoogleAuth } from "google-auth-library";

const METADATA_TOKEN_URL =
  "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token";

let authClient: GoogleAuth | null = null;

export async function getGcpAdcAccessToken(): Promise<string> {
  if (!authClient) {
    authClient = new GoogleAuth({
      scopes: ["https://www.googleapis.com/auth/cloud-platform"],
    });
  }
  const client = await authClient.getClient();
  const tokenRes = await client.getAccessToken();
  const token = typeof tokenRes === "string" ? tokenRes : tokenRes?.token;
  if (!token) {
    throw new Error("Failed to resolve GCP access token via ADC.");
  }
  return token;
}

export async function resolveGcpAccessToken(fetchFn?: typeof fetch): Promise<string> {
  if (!fetchFn && process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim()) {
    return getGcpAdcAccessToken();
  }
  try {
    const res = await (fetchFn ?? fetch)(METADATA_TOKEN_URL, {
      headers: { "Metadata-Flavor": "Google" },
    });
    if (res.ok) {
      const data = (await res.json()) as { access_token?: string };
      if (data.access_token) return data.access_token;
    }
  } catch {
    // Metadata server unavailable outside GCE/Cloud Run; fall back cleanly to ADC.
  }
  return getGcpAdcAccessToken();
}

For least privilege, each workload mounts its own JSON key via Kubernetes Secret at defaultMode: 0440 alongside fsGroup: 1001 so non-root Node.js processes can read the credential file without root permissions. One subtle IAM detail uncovered during live verification: Discovery Engine conversational search (conversations.converse) requires roles/discoveryengine.viewer rather than non-existent role aliases, whereas read-only cross-project telemetry dashboards bind strictly to viewer roles in the secondary GCP project.

Production War Stories: HPA Calibration, local-path-retain & Non-Root Alloy

Running real traffic surfaced three Kubernetes subtleties that synthetic tutorials rarely catch:

Defense-in-Depth NetworkPolicies & Multi-Tenant Isolation

Shared clusters hosting stateful databases alongside multi-tenant webhooks need strict east-west isolation. Public host firewalling allows only ports 22, 80, and 443—blocking the Kubernetes API, NodePorts, loopback registry, PostgreSQL, Redis, Prometheus, Loki, and Grafana externally—while CNI-enforced NetworkPolicy manifests isolate pods inside the cluster:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: afcom-db-ingress
  namespace: app-core
spec:
  podSelector:
    matchLabels:
      app: afcom-db
  policyTypes:
    - Ingress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: afcom-web
        - podSelector:
            matchLabels:
              app: afcom-db-backup
      ports:
        - protocol: TCP
          port: 5432
    - from:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: monitoring
      ports:
        - protocol: TCP
          port: 5432

With parallel policies on Redis (:6379) and the Django Prometheus endpoint (:9108), stateless namespaces can never reach relational tables or cache keys, and operational dashboards stay ClusterIP-only—accessed strictly on demand through short-lived ssh -L port-forwards.

Three-Provider Encrypted Backups & Full-Stack SRE Observability

Single-node convenience must never compromise disaster recovery. A nightly non-root backup CronJob eliminates single-provider exposure by splitting compute, ciphertext, and keys across three providers:

  1. Domain 1 (Bare-Metal Source): Runs pg_dump --format=custom against the database Service, pipes through openssl enc -aes-256-cbc -pbkdf2 -iter 200000 -salt, and verifies output size locally.
  2. Domain 2 (Cloudflare R2 Storage): Uploads ciphertext-only .dump.enc archives over TLS using an S3-compatible scoped token limited to one private bucket with a 30-day lifecycle expiration rule.
  3. Domain 3 (Independent Key Vault): Stores the symmetric decryption key solely in GCP Secret Manager and offline operator storage—never alongside R2 credentials. Full pg_restore --exit-on-error recovery drills verify restore integrity end-to-end.

Observability runs in a dedicated monitoring namespace using kube-prometheus-stack (15-day TSDB), Grafana Loki + Alloy (4 namespaces, 7-day retention), 13 Blackbox probes checking both public Cloudflare HTTPS URLs and internal cluster origins every 30 seconds, Django ASGI RED instrumentation with bounded route cardinality buckets, least-privilege pg_monitor PostgreSQL metrics, and 33 custom alerting rules firing to both Email and WhatsApp incident channels—including dead-man's-switch alerts when any backup job fails or misses its 27-hour window.

Frequently Asked Questions

How do you prevent dropped requests during k3s rolling deployments?

Combine maxUnavailable: 0 and maxSurge: 1 with a lifecycle.preStop command (such as sleep 5) plus lightweight startup and readiness probes. Kubernetes removes the terminating pod from Service endpoints while preStop holds listening sockets open long enough for iptables updates to propagate before SIGTERM closes active connections.

Can Kubernetes pods outside Google Cloud safely access Firestore and Vertex AI?

Yes. Replace metadata-server token fetches with a centralized GoogleAuth Application Default Credentials helper backed by a least-privilege service account JSON key mounted as a read-only Kubernetes Secret (defaultMode: 0440 with matching non-root fsGroup). No Compute Engine metadata endpoint is required.

Why separate encrypted database backups across three cloud providers?

Keeping source data on bare metal, uploading only AES-256-CBC encrypted dumps to Cloudflare R2 with scoped object keys, and storing the decryption passphrase exclusively in an isolated cloud Secret Manager ensures that compromising either the R2 bucket or a backup storage token cannot expose plaintext customer data.

What stopped HPA thrashing and premature scaling on Next.js pods?

Calibrating container CPU requests upward from 50m to 200m (with a 1 CPU limit) raised the 70% HPA trigger from 35m to 140m, absorbing short V8/Next.js boot bursts cleanly so idle pods settle at 0-2% utilization instead of pinning replicas at the maximum bound.

Explore related deep dives across our Cloud Engineer, GCP Professional Cloud Architect, Kubernetes & Helm Graceful Shutdown, Cloudflare Edge Security & Failover, Backend Engineer, AI Application Engineer, and Full Stack Engineer guides, or book an architecture sprint through the 1-Day Programming Service ($100 / Rp 1,000,000).


About the Author — Hire Aldian Fazrihady (Cloud Engineer, GCP Professional Cloud Architect, GCP Professional Data Engineer, Backend, AI & Full Stack Engineer)

Aldian Fazrihady is a Top-Rated Senior Cloud Engineer, GCP Professional Cloud Architect (Google Cloud Certified), GCP Professional Data Engineer (Google Cloud Certified), Backend Engineer (Python, Django, FastAPI, Go, PostgreSQL), AI Application Engineer (LLMs, RAG, MCP, Google ADK, LangGraph), and Full Stack Engineer (React, Next.js, TypeScript) with 25+ years of production software engineering experience.

Hire Aldian Fazrihady on Upwork | Book 1-Day Programming Service ($100 USD / Rp 1.000.000) | View Live AI Portfolio | Send a Direct Message

Related Engineering Articles

Engineering Role Pillar Guides & Category Hubs