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:
- Stateful Django ASGI Stack (
afcom-web): Two Daphne replicas fronted by NodePort:30080talk over ClusterIP Services to an in-clusterStatefulSetrunningpgvector/pgvector:pg15(85 tables plus vector embeddings) and aRecreate-strategyredis:7-alpinepod backed by AOF+RDB persistence. - Two Stateless Next.js 16 Applications: Multi-domain web applications run two replicas each behind NodePorts
:30081and:30082with zero local PersistentVolumeClaims, keeping transactional state, authentication, and LLM APIs on managed Cloud Firestore, Firebase Auth, Vertex AI, and Discovery Engine. - Cloudflare Free + Caddy SNI Reverse Proxy: With built-in Traefik disabled at k3s install time, a host-level Caddy systemd service terminates 15-year Cloudflare Origin Certificates under
Full (strict)TLS, proxies SNI hostnames cleanly to localhost NodePorts, and stamps 1-year immutable headers on compiled static chunks.
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:
- HPA Oscillation from Undersized CPU Requests: Setting
requests.cpu: 50mplaced the 70% HPA autoscale threshold at just35m. Normal Next.js container warmup during rolling updates immediately spiked past190%of request, pinning HPA at max replicas and raising pending throttling alerts. Raising web pods to200mCPU request /1CPU limit (and internal 15-minuteCronJobrunners from100mto500mlimit) settled steady-state HPA utilization to0-2%. - Protecting Database PVCs with
local-path-retain: Built-in k3slocal-pathusesreclaimPolicy: Delete, meaning an accidental PVC removal wipes host files. Stateful PostgreSQL (20Gi) and Redis (1Gi) use a customStorageClass/local-path-retain(reclaimPolicy: Retain), mountPGDATAin a subdirectory to keep filesystem artifacts likelost+foundout ofinitdb, and attach a256Mimemory-backed/dev/shmvolume so parallel Postgres queries avoid the64Micontainer default. - Non-Root Grafana Alloy Logging Without Host Log Paths: Instead of mounting host
/var/log/podswith elevated privileges, Alloy uses RBAC-scopedloki.source.kubernetesover the API server inside a non-root container (readOnlyRootFilesystem: true) by mountingemptyDirat the parent state directory/var/lib/alloywithfsGroup: 10001.
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:
- Domain 1 (Bare-Metal Source): Runs
pg_dump --format=customagainst the database Service, pipes throughopenssl enc -aes-256-cbc -pbkdf2 -iter 200000 -salt, and verifies output size locally. - Domain 2 (Cloudflare R2 Storage): Uploads ciphertext-only
.dump.encarchives over TLS using an S3-compatible scoped token limited to one private bucket with a 30-day lifecycle expiration rule. - 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-errorrecovery 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).