Goal#

Take an app that runs locally with docker compose up, and get it running on the homelab at https://myapp.lab.paulustech.uk. After that, every push to main tests it, builds it and deploys it, with nobody touching a server.

The example in this post is a real side project, renamed myapp. It has:

  • three Spring Boot services and a gateway in front of them
  • a Vue frontend served by nginx
  • Postgres, Redis, and Keycloak for sign-up and login

If your app is a single container, skip to the shortcut.

How it works#

git push runs tests and builds images on a self-hosted runner, pushes them to a private registry, and commits the new tag to homelab-gitops. Argo CD sees the commit and syncs k3s, which pulls the images.

  1. I push to main on GitHub.
  2. GitHub hands the job to the self-hosted runner, on a CI VM in the homelab. It runs the tests and builds one Docker image per component.
  3. The runner pushes the images to a private registry on the same VM. Each image is tagged with the first 12 characters of the commit SHA, so every build gets its own tag.
  4. The runner commits that tag into homelab-gitops, the repo that holds every Kubernetes manifest for the cluster.
  5. Argo CD, running inside k3s, polls that repo every 3 minutes and notices the commit.
  6. Argo CD applies the change, so the Deployments now point at the new tag.
  7. k3s pulls the new images from the registry and swaps the pods.

The pipeline never logs into the cluster. It only writes to git. Git is the single source of truth: to see what’s deployed, read the repo. To roll back, revert the commit.

Here’s how a request finds the app once it’s running:

Pi-hole answers the k3s node’s IP for any lab.paulustech.uk name. Traefik terminates TLS with the wildcard certificate and routes by hostname to the web pod or Keycloak.

  • DNS: Pi-hole has one wildcard rule: anything under *.lab.paulustech.uk points at the k3s node. A new hostname needs no DNS change.
  • TLS: cert-manager keeps one wildcard certificate for *.lab.paulustech.uk, issued by Let’s Encrypt through a DNS-01 challenge. Traefik serves it for every hostname.
  • Routing: Traefik reads the hostname and sends the request to the matching Kubernetes Service. Each Ingress lists the hostnames it owns.

Prereqs#

These exist already and don’t change per app:

  • The k3s node with Argo CD, Traefik, cert-manager, Sealed Secrets and CloudNativePG installed
  • The homelab-gitops repo, watched by Argo CD
  • A self-hosted GitHub Actions runner, registered to the GitHub org
  • A small secrets service for CI, which hands the runner the registry address and a GitHub token that can push to homelab-gitops
  • Locally: kubectl pointed at the cluster, plus kubeseal

The app itself needs:

  • A Dockerfile for each image
  • A health endpoint for each service (Spring Boot gives you /actuator/health)
  • Configuration from environment variables, not baked-in files

If the app already runs with docker compose up, it has all three.

Steps#

1. Map the compose file to Kubernetes#

Every compose concept has a direct equivalent. Go through compose.yml one service at a time:

compose.ymlKubernetes
a servicea Deployment (runs the container) + a Service (gives it a stable name)
image: / build:image: registry.lab.paulustech.uk/myapp-<name>:<tag>
environment:env: values, or secretKeyRef for anything secret
named volumePersistentVolumeClaim, storageClassName: local-path
healthcheck:readinessProbe / livenessProbe / startupProbe
mem_limit:resources.limits.memory
ports: to the outsidean Ingress with a hostname
depends_on:nothing: pods retry until what they need is up
the postgres containera CloudNativePG Cluster
a reverse proxy (Caddy, nginx edge)nothing: Traefik does TLS and routing

Keep the Service names from compose. Apps hard-code them, for example proxy_pass http://gateway-service:8080 or a JDBC URL with redis as the hostname. Inside the same namespace, gateway-service resolves to the Service with that name, so nothing in the app needs to change.

2. Give the app its own namespace#

Because the app hard-codes names like redis and keycloak, it gets a namespace to itself so they can’t clash with another app’s.

platform/namespaces/myapp.yaml in homelab-gitops:

apiVersion: v1
kind: Namespace
metadata:
  name: myapp
---
apiVersion: v1
kind: ResourceQuota
metadata:
  name: quota
  namespace: myapp
spec:
  hard:
    requests.cpu: "2"
    requests.memory: 3Gi
    limits.memory: 6Gi
---
apiVersion: v1
kind: LimitRange # defaults for any container that doesn't set resources
metadata:
  name: defaults
  namespace: myapp
spec:
  limits:
    - type: Container
      defaultRequest: { cpu: 50m, memory: 64Mi }
      default: { memory: 256Mi }

The quota stops one app from eating the node. Add up the requests of everything you’re about to deploy, then leave some headroom.

3. Write the manifests#

Create one folder: stacks/myapp/myapp/. Argo CD has an ApplicationSet that turns every stacks/<namespace>/<app>/ folder into an Argo CD app. A new folder plus a push is all it takes. I use one file per component:

stacks/myapp/myapp/
├── db.yaml              Postgres (CloudNativePG)
├── redis.yaml
├── keycloak.yaml        + the realm import as a ConfigMap
├── services.yaml        the Spring Boot services
├── web.yaml             nginx + the frontend build
├── mailpit.yaml         catches outgoing email
├── ingress.yaml
└── secrets.sealed.yaml

A service looks like this. The other services follow the same pattern:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: gateway-service
spec:
  replicas: 1
  revisionHistoryLimit: 1 # keep one old ReplicaSet; git is the real history
  selector:
    matchLabels: { app.kubernetes.io/name: gateway-service }
  template:
    metadata:
      labels: { app.kubernetes.io/name: gateway-service }
    spec:
      containers:
        - name: gateway-service
          image: registry.lab.paulustech.uk/myapp-gateway:5d226c2700ec # CI rewrites this tag
          env:
            - name: OIDC_ISSUER
              value: https://myapp-id.lab.paulustech.uk/realms/myapp
            - name: REDIS_PASSWORD
              valueFrom:
                secretKeyRef: { name: myapp-app, key: REDIS_PASSWORD }
          ports:
            - { name: http, containerPort: 8080 }
          startupProbe: # give the JVM up to 5 minutes on first boot
            httpGet: { path: /actuator/health/liveness, port: http }
            periodSeconds: 10
            failureThreshold: 30
          readinessProbe:
            httpGet: { path: /actuator/health/readiness, port: http }
          livenessProbe:
            httpGet: { path: /actuator/health/liveness, port: http }
          resources:
            requests: { cpu: 100m, memory: 384Mi }
            limits: { memory: 768Mi }
---
apiVersion: v1
kind: Service
metadata:
  name: gateway-service # same name as in compose
spec:
  selector: { app.kubernetes.io/name: gateway-service }
  ports:
    - { name: http, port: 8080, targetPort: http }

Anything with a volume (Redis, uploaded files) also gets a PVC and strategy: { type: Recreate }. A local-path volume can only be mounted by one pod at a time, so the old pod has to stop before the new one starts.

4. Postgres: one cluster, several databases#

The app wants three databases, each with its own owner. Locally an init.sh script creates them. On k3s, the CloudNativePG operator does it from YAML:

apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
  name: myapp-db
spec:
  instances: 1
  imageName: ghcr.io/cloudnative-pg/postgresql:17
  bootstrap:
    initdb: # first database + owner
      database: profiles
      owner: profile_app
      secret: { name: myapp-db-profile }
  managed:
    roles: # the other owners
      - name: photos_app
        ensure: present
        login: true
        passwordSecret: { name: myapp-db-photos }
  storage: { storageClass: local-path, size: 5Gi }
---
apiVersion: postgresql.cnpg.io/v1
kind: Database
metadata:
  name: photos
spec:
  name: photos
  owner: photos_app
  cluster: { name: myapp-db }

Apps connect to myapp-db-rw:5432. CloudNativePG creates that Service, and it always points at the primary.

5. Secrets: generate, seal, commit#

Nothing secret goes into git in plain text. Sealed Secrets encrypts each value with a key that only the cluster holds. The encrypted file is safe to commit, and the controller in the cluster turns it back into a normal Secret.

cd stacks/myapp/myapp
r() { openssl rand -hex 24; }

# Database passwords: basic-auth secrets, the format CloudNativePG expects
kubectl create secret generic myapp-db-profile -n myapp \
  --type=kubernetes.io/basic-auth \
  --from-literal=username=profile_app --from-literal=password="$(r)" \
  --dry-run=client -o yaml | kubeseal -o yaml > secrets.sealed.yaml

# Everything else in one secret
echo "---" >> secrets.sealed.yaml
kubectl create secret generic myapp-app -n myapp \
  --from-literal=REDIS_PASSWORD="$(r)" \
  --from-literal=GATEWAY_CLIENT_SECRET="$(r)" \
  --dry-run=client -o yaml | kubeseal -o yaml >> secrets.sealed.yaml

--dry-run=client -o yaml builds the Secret without sending it anywhere. kubeseal encrypts it. The random values never appear on screen. They don’t need to, because nobody has to type them: the apps read them from the Secret.

To read one later, for example the Keycloak admin password:

kubectl -n myapp get secret myapp-app -o jsonpath='{.data.KEYCLOAK_ADMIN_PASSWORD}' | base64 -d

6. Hostnames and the Ingress#

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: myapp
  annotations:
    traefik.ingress.kubernetes.io/router.entrypoints: websecure
spec:
  ingressClassName: traefik
  tls:
    - hosts: [myapp.lab.paulustech.uk, myapp-id.lab.paulustech.uk]
  rules:
    - host: myapp.lab.paulustech.uk
      http:
        paths:
          - path: /
            pathType: Prefix
            backend: { service: { name: web, port: { name: http } } }
    - host: myapp-id.lab.paulustech.uk # Keycloak: public paths only
      http:
        paths:
          - path: /realms
            pathType: Prefix
            backend: { service: { name: keycloak, port: { name: http } } }
          - path: /resources
            pathType: Prefix
            backend: { service: { name: keycloak, port: { name: http } } }
  • No secretName is needed: Traefik serves the wildcard certificate by default.
  • Only /realms and /resources reach Keycloak. Anything else on that host, including the admin console, gets a 404. To use the admin console, tunnel in instead: kubectl -n myapp port-forward svc/keycloak 8080, then open http://localhost:8080/admin.

7. The CI workflow#

This goes in the app repo as .github/workflows/deploy.yml. Copy it to a new app and change APP, STACK and the test and build steps.

name: Build + Deploy
on:
  push: { branches: [main] }
  workflow_dispatch:

env:
  APP: myapp                       # images: $REGISTRY/myapp-<name>:<tag>
  STACK: stacks/myapp/myapp        # where the manifests live in homelab-gitops

jobs:
  test:
    runs-on: [self-hosted, homelab]
    steps:
      - uses: actions/checkout@v4
      # ... setup-java / setup-node, then the project's own checks

  build-and-deploy:
    needs: test
    runs-on: [self-hosted, homelab]
    steps:
      - uses: actions/checkout@v4

      # The runner image has no buildx plugin; Dockerfiles with RUN --mount need it
      - uses: docker/setup-buildx-action@v3
        with: { version: latest, driver: docker, install: true }

      - name: Read registry from vault
        id: vault
        run: |
          curl -fsS "$VAULT_URL/api/secrets" \
            -H "Authorization: Bearer $VAULT_RUNNER_TOKEN" \
            | jq -er '"registry=" + .REGISTRY_URL' >> "$GITHUB_OUTPUT"

      - name: Build + push images
        env: { REGISTRY: "${{ steps.vault.outputs.registry }}" }
        run: |
          TAG="${GITHUB_SHA::12}"
          docker build -t "$REGISTRY/$APP-web:$TAG" ./frontend
          docker push "$REGISTRY/$APP-web:$TAG"
          # ... one build + push per image

      - name: Bump image tags in homelab-gitops
        run: |
          set -euo pipefail
          TAG="${GITHUB_SHA::12}"
          GITOPS_TOKEN=$(curl -fsS "$VAULT_URL/api/secrets" \
            -H "Authorization: Bearer $VAULT_RUNNER_TOKEN" | jq -er '.GITOPS_TOKEN')
          echo "::add-mask::$GITOPS_TOKEN"
          dir="$RUNNER_TEMP/homelab-gitops"
          git clone -q --depth 1 \
            "https://x-access-token:${GITOPS_TOKEN}@github.com/<your-org>/homelab-gitops.git" "$dir"
          cd "$dir"
          # every "image: <registry>/myapp-<name>:<anything>" gets the new tag
          sed -i -E "s#(image: [^[:space:]]+/${APP}-[a-z]+):[^[:space:]]+#\1:${TAG}#" "$STACK"/*.yaml
          git diff --quiet && exit 0
          git -c user.name="$APP-ci" -c user.email="[email protected]" \
            commit -qam "chore: deploy $APP ${TAG}"
          git push -q || { git pull -q --rebase && git push -q; }

The GitHub token is a fine-grained personal access token. It’s scoped to the homelab-gitops repo only, with permission to read and write its contents. It lives in the vault, never in the app repo.

8. First deploy#

The manifests need a tag before the first image exists, so do it in this order:

# 1. In the app repo: commit the workflow, but don't push yet
git add .github/workflows/deploy.yml && git commit -m "feat: deploy to the homelab"
TAG=$(git rev-parse HEAD | cut -c1-12)

# 2. In homelab-gitops: use that tag, validate, push
sed -i "s#:TAG\$#:$TAG#" stacks/myapp/myapp/*.yaml
./scripts/validate.sh
git add -A && git commit -m "feat: deploy myapp" && git push

# 3. Back in the app repo: push, which starts CI
git push

Argo CD creates everything within a few minutes. Postgres, Redis and Keycloak start straight away. The app pods show ImagePullBackOff until CI has pushed their images, then they start on their own. After that it’s just git push.

9. Check it#

kubectl -n myapp get pods                      # everything Running, 1/1
kubectl -n argocd get applications.argoproj.io myapp
curl -sI https://myapp.lab.paulustech.uk     # 200

Then sign up in the browser. The verification email lands in Mailpit at https://myapp-mail.lab.paulustech.uk. Click the link, and you’re logged in to the app. That one flow checks everything: DNS, TLS, Traefik, Keycloak, mail, the gateway’s session in Redis, and the API reading Postgres.

Shortcut: single-container apps#

For one container with an optional disk, skip the hand-written manifests. homelab-gitops has a generic Helm chart, so a whole app is about five lines:

cp -r workloads/apps/whoami workloads/apps/myapp
# workloads/apps/myapp/values.yaml
image:
  repository: registry.lab.paulustech.uk/myapp
  tag: 5d226c2700ec
port: 8080
probePath: /health
ingress:
  host: myapp.lab.paulustech.uk

Push, and it’s live at that hostname.

Gotchas#

  • the --mount option requires BuildKit. The runner’s Docker CLI has no buildx plugin, so docker build falls back to the old builder. That builder doesn’t understand RUN --mount=type=cache in a Dockerfile. docker/setup-buildx-action with driver: docker installs buildx for the job and builds with the host’s BuildKit, so the images still land in the local store for docker push.
  • The wildcard certificate covers one level. myapp-id.lab.paulustech.uk works. id.myapp.lab.paulustech.uk doesn’t, and the browser shows a certificate error. Use dashes, not dots.
  • No depends_on. Keycloak restarted twice because Postgres wasn’t ready yet. That’s normal: Kubernetes restarts the pod until its dependencies are up. Give slow starters a generous startupProbe, so the liveness probe doesn’t kill them while they’re still booting.
  • Pods can reach the public hostnames. The services check login tokens against https://myapp-id.lab.paulustech.uk. Pods resolve that name through Pi-hole and reach Traefik on the node’s IP, so it works with no extra config.
  • Java memory follows the container limit. The images set -XX:MaxRAMPercentage=70, so the heap is 70% of limits.memory. Raise the limit, not -Xmx.
  • Keep the tags pinned. Always use a commit-SHA tag, never :latest. Otherwise Argo CD can’t tell anything changed, and rolling back means guessing which build was running.
  • kubectl get app is the wrong command. Rancher also defines an apps resource, so the short name is taken. Use kubectl get applications.argoproj.io.
  • Mail stays local. Mailpit catches every email, so nothing leaves the LAN. Real email means real SMTP credentials, in the Keycloak realm and in the services’ SMTP_* settings.

References#