CODEMOWERS

A field guide for software that runs.

Zen of
Kubernetes.

Build deliberately. Let the platform do its job.

Practical guidance for developing and deploying on bare-metal Kubernetes, also useful on managed cloud and local clusters. Discover the target platform’s capabilities and policies before adapting examples.

  1. Repeating a default in code, an image and a chart makes it unclear which setting controls behavior. Deployment overrides should express actual differences. Read the guidance →
  2. Run the application directly as PID 1, with threads where appropriate. Keep independent process lifecycles in separate containers. Read the guidance →
  3. Keep scheduling, supervision and worker replication in the platform. Application containers should execute work, not run their own orchestration system. Read the guidance →
  4. A replacement Pod must be able to resume service without the old container filesystem. Put durable data in deliberately provisioned backing services. Read the guidance →
  5. Generated secrets and secret stores both work. Keep credentials independent of images and make rotation quick: provision replacements, update every consumer, then revoke old credentials. Read the guidance →
  6. Alert on measurable symptoms with metrics, investigate events with logs, and use traces to locate latency and bottlenecks across service calls. Keep credentials and sensitive payloads out of telemetry. Read the guidance →
  7. Recover only where the failure is understood. Empty results and success acknowledgements must not disguise broken work. Read the guidance →
  8. A worker can finish a side effect and die before acknowledging it. Repeated delivery must not charge twice or duplicate data. Read the guidance →
  9. Readiness controls traffic; liveness triggers restarts. A shared dependency outage should not restart every application replica. Read the guidance →
  10. Stop accepting work on SIGTERM and finish or return in-flight work within the deadline. Correctness must also survive a forced stop. Read the guidance →
  1. Use an external identity provider; do not embed an IdP or implement password handling in the application. Keep tenant, record and operation authorization in the application. Read the guidance →
  2. Design for multiple replicas, rolling updates and node failures from the start. Coordinate shared work and keep backing services resilient too; extra application replicas alone do not make a system highly available. Read the guidance →
  3. Encrypt in-cluster traffic and verify certificates and hostnames. Configure client trust and renewal handling; record the separate Prometheus transport choice. Read the guidance →
  4. An example or platform name does not prove an operator is installed, authorized or healthy. Inspect APIs, controllers and policy bindings. Read the guidance →
  5. Staging and production should run the artifact that was checked. Record image and configuration revisions so a release can be reproduced. Read the guidance →
  6. The application process must accept both address families; a Kubernetes Service cannot fix an IPv4-only listener. Local Compose may remain IPv4-only. Read the guidance →
  7. Use namespace-local requests for operator or provider-managed databases, caches and identity registrations. Platform administrators manage the shared services. Read the guidance →
  8. Keep platform configuration in discovered, applicable policies. The deployment guide covers networking, TLS, trust, security, storage and ingress conventions, with explicit values when policies do not supply them. Read the guidance →
  9. Treat both as shared infrastructure. Isolate instances with release-specific names and selectors; leave shared operators and namespace lifecycle to the platform. Read the guidance →

From source to service

The guide

The guide

Developing

Back to contents ↑

These conventions target new applications; assess existing ones case by case (building/general).

Scope #

The repository, its instructions and these advisories are context, not a task. Do what the user asked; if the request is unclear, ask before changing, building or deploying. Read an advisory when the agreed work needs its decisions.

Decisions and configuration #

  • One version-controlled codebase per application, deployed many times; environment differences live in release configuration, not source copies.
  • Read the project's recorded decisions first and ask only about open ones: authentication (developing/architecture), native versus portable dependencies (deploying/storage) and Prometheus transport (deploying/observability). Record each choice, its reason and nonsecret settings in the project's AGENTS.md.
  • Configure endpoints, credentials and environment behavior at runtime, so a backing service can be swapped without a code change. Use the same variable names everywhere and keep each default in one layer.
  • Do not add single-use helper wrappers; extract helpers only for actual reuse.
  • Write YAML as indented block mappings and sequences. End text files with a newline.
  • Git: developing/git.

Failures and lifecycle #

  • Handle only known, recoverable errors, at the operation that can recover, with narrow try blocks. Rethrow anything unrecognized.
  • Let unexpected failures fail the request, job or process. Never turn them into success, empty results, blind retries or log-and-continue. Clean up with finally, defer or context managers.
  • Run the database operation directly and rely on constraints and specific errors, rather than a preflight existence check.
  • Start fast. On SIGTERM stop accepting work and finish or return in-flight work before the deadline. Make jobs idempotent so a retry after abrupt termination has no duplicate effects.

Container process model: building/general. Scheduling and resources: deploying/workloads. Listeners and TLS: deploying/networking.

Choose the authentication boundary #

Before implementing authentication, ask the user to choose between a backend for frontend (BFF) and direct OIDC/OAuth API access, and record the choice (developing/general) with its clients, audiences, scopes and token ownership.

Pattern Fits Costs
BFF: browser session cookie, backend holds tokens One first-party browser UI HttpOnly cookies, CSRF protection, session lifecycle, an extra hop
Direct API: clients hold access tokens Browser, mobile, CLI and integration clients Audience and scope design, CORS, tokens exposed to page JavaScript

Both use an external OIDC provider with Authorization Code and PKCE (browser app guidance). Business authorization stays in the backend either way.

Delegate identity, enforce authorization #

  • Accounts and login belong to an external identity provider. Never implement passwords, password reset or a parallel local login, and never bundle an IdP into the application. Passmower and authentik are providers; Pomerium is an access proxy in front of one. Discover which exist (deploying/discovery); registrations follow deploying/storage.
  • Key application data to the verified (iss, sub) and enforce tenant, ownership and permissions; being authenticated grants no record access.
  • Agree on API audiences and minimal scopes such as documents:read, and check that the provider actually grants them.
  • Validate access tokens for issuer, audience, expiry and scopes; ID tokens are not access tokens. A BFF enforces the same permissions rather than proxying a broad service credential.

Keep signed transfers direct #

  • After authorizing an object operation, hand the client a short-lived presigned URL for direct transfer; storage credentials stay server-side. Configure CORS for the real browser origins.
  • Sign for the client-reachable HTTPS endpoint and never rewrite a signed URL (SigV4 query auth).
  • Do not relay S3/MinIO transfers through the application; fix a missing public endpoint instead.

Production data #

Never commit production data, including in tests, fixtures, examples, docs or snapshots. Real cluster identifiers, hostnames, IP addresses, kubeconfigs, namespace names and kubeconfig context names must not be committed unless the user explicitly authorizes those specific values. Discovering them through MCP, kubeconfig or a live cluster is not permission to publish them. Use synthetic hostnames, identities, IDs, payloads and logs in committed examples and tests; keep environment-specific configuration in ignored local files.

Local verification before commit #

Before staging changes as ready or committing them, inspect the repository's CI workflows and guidance. Run as many applicable CI checks locally as possible, using the same tool versions, configuration, scope and generated inputs. For broad changes, run the full locally executable suite: lint, static analysis, type checks, tests (including race checks where configured), builds, and any chart, rule or release-script validation. Tests and vet do not replace lint.

Review .gitignore and .dockerignore, including ignore files for individual Docker build contexts. Keep credentials, local configuration, caches and unintended generated artifacts out of Git and image build contexts, while preserving required source and build inputs. Check the staged file list and ensure required new files are included.

Look for existing project-local tools as well as tools on PATH before declaring a check unavailable. Obtain missing tools when feasible within the task's permissions. Fix failures and rerun the affected checks against the final revision. Report any omitted check and its reason explicitly; never report an omitted check as passing. Local validation does not publish releases, push images or deploy workloads.

History and integration #

Keep linear history: rebase feature work onto the target branch, integrate by rebase or fast-forward, and squash fixups when a request is one logical change. Ordinary merge commits are only for large projects where a designated integrator resolves conflicts between many contributors (distributed workflows); record that exception in the contribution rules.

Review and test the final integrated revision. A merge can contain edits from neither parent; inspect it with git show --remerge-diff <commit>.

Rewrite only feature branches you own or whose collaborators agree. Never rewrite published integration or release history. Push rewritten branches with git push --force-with-lease, and for a shared branch with --force-with-lease=<branch>:<expected-commit>.

Release tags #

Tag releases v<major>.<minor>.<patch>, such as v1.2.3, following semantic versioning and the existing series. List them with git tag --list 'v*' --sort=version:refname. Mark prereleases consistently, such as v1.3.0-rc.1. Create annotated tags on the tested release commit and never move or reuse a published tag. Publication follows building/ci.

Repository layout #

Choose a monorepo or one repository per service by ownership and how often changes span services, not by the number of images. A monorepo commit can change several services but does not make their deployment atomic. Either way, record each image's source revision and digest and the compatible digests of a release.

Hosting configuration #

Configure the forge to integrate pull requests without merge commits; local pull.rebase does not change its merge button. Protect target branches separately against direct pushes.

Host Settings
GitHub Settings → General → Pull Requests: disable merge commits, enable rebase merging (squash optional). Enable Require linear history in the branch ruleset (rebase settings).
GitLab Settings → Merge requests → Merge method: Fast-forward merge. Semi-linear history still creates merge commits (merge methods).
Gitea Disable Merge and Rebase then merge; make Rebase the default. For new repositories set DEFAULT_MERGE_STYLE = rebase under [repository.pull-request] in app.ini.

User configuration #

[user]
    email = jane@example.com
    name = Jane Doe

[pull]
    rebase = true

[includeIf "gitdir:~/company-a/"]
    path = ~/company-a/gitconfig

Conditional includes override the identity for repositories under a directory. git config --show-origin --get <key> shows where a setting comes from.

  • Serve HTTP health/readiness endpoints such as /health and /ready on the internal listener defined in developing/metrics, separate from public application traffic. Wire them into Compose’s healthcheck directive for local use and the corresponding Kubernetes probes. Use a check command available in the image; do not assume a shell or curl exists in a minimal runtime.
  • Keep checks local, cheap and deterministic. Do not query databases or other backing services; a dependency outage must not trigger mass application restarts.
  • Readiness reports whether initialization is complete and the process accepts work; mark it unavailable when draining. Return a success status only while ready and a failure status otherwise.
  • Use a startup probe only when initialization needs a separate allowance before ordinary probes begin. Avoid liveness probes by default; add one only for a demonstrated local failure that restarting can repair. Check process progress, not dependency availability.

Apply developing/general for configuration and lifecycle.

  • Propagate request/job cancellation through contexts and stop background goroutines during shutdown. Bound concurrent work and connection pools.
  • Handle expected errors at the operation that can recover; return unexpected errors with context. Do not ignore errors or use broad panic recovery to keep failed work running.
  • Use one metrics registry across handlers and workers in the process; follow developing/metrics for its listener. Frameworks such as Gin are optional integrations, not deployment requirements.

Before starting a new Java application for Kubernetes, check whether the JVM's runtime model fits the workload.

  • The JVM manages its own heap and rarely returns memory to the operating system after a garbage-collection cycle. Container memory metrics such as working set and RSS therefore show how much heap the JVM has reserved, not how much memory the application is actually using. This makes them unreliable for right-sizing requests and limits, detecting leaks, or scaling on memory.
  • Startup and JIT warm-up delay readiness and make new replicas slower than established ones. This weakens autoscaling, rolling updates and recovery after rescheduling.
  • Container sizing depends on JVM settings such as -XX:MaxRAMPercentage, garbage collector choice and off-heap allocations. Memory behaviour then depends on configuration as well as code, and each component needs tuning.

These costs exist to support long-running processes on dedicated hosts. When replicas are small, short-lived and frequently rescheduled, the costs remain but the benefit largely disappears. Record why Java is the right choice when starting a new application.

For existing Java applications, apply developing/general for configuration, lifecycle and failures, and developing/metrics for metrics. Expose the JVM's own heap, garbage-collection and thread metrics, and use them rather than container memory metrics to judge memory use.

Apply developing/general for configuration, failures and shutdown, and building/languages/nodejs for the production entrypoint.

  • Keep blocking or CPU-intensive work off the request event loop. Bound outstanding promises, queue consumption and connection pools; an async function does not make synchronous work nonblocking.
  • Await or explicitly supervise asynchronous work so failures reach the request/job owner. Do not consume arbitrary promise rejections with catch-and-continue handlers.
  • Close listeners and drain tracked work on SIGTERM. Choose the framework for application needs and keep health/metrics on the internal listener in developing/metrics.

Follow building/general for the single-process contract and legacy exceptions. PHP-FPM's master/worker model, even with pm.max_children = 1, does not meet that contract for new services; do not bundle it with nginx and a supervisor. See PHP-FPM configuration.

Example: Framework X #

Framework X illustrates a long-lived PHP service using its ReactPHP server and direct php public/index.php entrypoint, rather than FPM integration. Choose a framework to fit the application.

Keep I/O asynchronous throughout the request path; blocking libraries still block the event loop. Use the process's shared metrics registry and bounded shutdown described in developing/metrics and developing/general.

Apply developing/general for configuration, failures and lifecycle, and building/languages/python for packaging.

  • Prefer async I/O with compatible libraries throughout the request path. Do not call blocking database, storage, image-processing or inference operations directly on the event loop. For synchronous applications, retain a single execution thread until concurrency can be introduced correctly.
  • Justify worker threads with measurements and the actual runtime/library behavior. On GIL-enabled runtimes, CPU parallelism requires operations that release the GIL; importing a library alone proves nothing. Bound tasks, thread pools and connection pools; avoid unbounded executors.
  • Follow the single-process contract in building/general; do not add uWSGI worker pools or process supervisors for new services.

Example: Sanic #

Sanic is one async HTTP option. Use sanic server:app --host=:: --port=8000 --single-process or app.run(host="::", port=8000, single_process=True) to disable its worker manager and auto-reloader. Its ordinary one-worker mode still includes a manager process. See Running Sanic.

Apply developing/general for failure handling and lifecycle. Choose a framework and async runtime for the application's libraries and workload.

  • Use typed errors and propagate failures with context.
  • Keep blocking work out of async request paths. Bound tasks and connections; propagate cancellation and join application tasks during shutdown.
  • Validate required configuration at startup; listener requirements belong to deploying/networking.

Example: Rocket #

Rocket applications may use rocket::build() with mounted handlers and configure through Rocket.toml or ROCKET_* variables. Set the deployment listener explicitly rather than inheriting a development bind address.

When using rocket_prometheus, attach instrumentation and export from the same registry, with the internal listener required by developing/metrics. Other frameworks use their equivalent hooks. Packaging: building/languages/rust.

  • Develop, build and check through the project's Skaffold or Compose workflow. Agents never install runtimes, packages or backing services on the host; installs happen in build containers. Lockfile-only commands are fine.
  • Compose mirrors production's components, dependency versions and variable names; development images may add debug tools and hot reload. It runs without TLS and may be IPv4 only.
  • Keep .env files untracked and document startup, checks and required configuration.

Optional discovery from local kubeconfig #

For a tool that finds installations in the user's clusters:

  • Make it opt-in with a flag and a Compose override; normal startup needs no Kubernetes credentials, and no cluster endpoints are committed.
  • Mount kubeconfig read-only with the certificate files it references, plus any exec credential helper; only its cache may be writable.
  • Use each context's credentials for bounded reads of the application's installation marker, such as a named Service. Take public endpoints from advertised metadata or routing resources, never from context names or API URLs. Never change the current context.
  • Show every context as installed, missing, forbidden or unreachable. Credentials stay server-side; the browser gets context names, status and public endpoints.

Use logs for triage: record enough context to investigate what happened and why. Use developing/metrics for alerting on measurable symptoms.

  • A healthy application logs nothing: no access logs, success messages, banners or periodic status, from the framework and libraries too. Verbose diagnostics are opt-in; unexpected failures are logged with the context to triage them.
  • Never log requests to the internal metrics and health listener.
  • No ANSI colors or terminal control sequences in Kubernetes logs.
  • Write to stdout/stderr; let the runtime collect, rotate and retain logs. Do not write container-local log files or duplicate runtime timestamps.
  • Choose plain text or structured JSON for the application's consumers; plain text alone is not a defect. Use meaningful severity levels; exclude credentials and sensitive payloads.
  • Measure repetitive events with metrics instead of producing a log record for every occurrence; see developing/metrics.

Use metrics for alerting: measure symptoms such as failure rates, latency and stalled work, with thresholds tied to actionable operational needs. Use developing/logging for the context needed to triage an alert.

  • Expose Prometheus metrics through the chosen framework's integration or client library. Use one shared, thread-safe registry for all application execution in the container; a scrape must not represent only the worker that answered.
  • Serve metrics and health checks on a separate internal port, never on the public listener or through Ingress. A separate port is also what lets NetworkPolicy tell monitoring from application traffic (deploying/networking). Scraping: deploying/observability.
  • Exclude sensitive data from names, labels, values, help text and exemplars: no identities, emails, IP addresses, credentials, tokens, bodies, raw URLs or query strings. Use bounded categories such as route templates, operations and status codes.
  • Measure request latency, request/response sizes, failures and useful business activity such as import throughput. Bound label cardinality. Leave container memory and filesystem usage to runtime monitoring.

The guide

Building

Back to contents ↑

Reproducible images #

  • Pin base-image versions and declare every dependency and system library. Commit lockfiles and install with a locked mode that fails on disagreement.
  • Install dependencies and compile assets during the build, in multiple stages; the final image holds only runtime files. Ship a static executable where possible.
  • Never install packages when a Pod starts: a restart must launch from the image alone. Include required runtime libraries, such as PyTorch for an application that imports it, but keep model weights and other data out (below).
  • Keep .dockerignore at the build-context root. Exclude Git metadata, host build outputs, caches, local configuration and credentials; keep sources, manifests, lockfiles and required assets.
  • Keep .gitignore for generated and private files. Never copy registry credentials or SSH keys into a layer.
  • Build tooling: developing/local-development. Publication: building/ci.

Separate executable code from data #

  • Package model weights, map datasets and similar large assets as data-only OCI images, not in the application image.
  • Version data images separately and record compatible digests together in a release. Keep their preparation recipes and source checksums in Git. A data image needs no runtime or entrypoint.
  • Mount them as image volumes (deploying/workloads).

Dockerfile examples #

The language sections show the lolcatz Dockerfiles. Adapt contexts, dependencies and assets to the application.

Runtime contract #

  • One application process per container, launched directly with exec-form ENTRYPOINT/CMD so it receives SIGTERM as PID 1. A setup script, if unavoidable, ends with exec. No init wrappers such as tini; an application that starts subprocesses reaps them.
  • The UID/GID comes from the deployment, preferably platform policy. Do not create users or set USER in the Dockerfile, and do not chown code. Expect a read-only root filesystem with explicit writable mounts (deploying/security).
  • CA certificates and trust paths never go in images, including scratch images. Admission policies or deployment values mount them at runtime (deploying/networking).

Porting legacy applications #

These rules target new applications. A ported application may keep a deviation, such as a fixed UID, a writable directory or a startup wrapper, when changing it is outside the agreed scope. Inspect its process model, identity, filesystem, state and lifecycle; record each retained deviation and its reason; verify startup, health, shutdown, upgrade and recovery. Do not turn a legacy workaround into the default for new services.

Separate development and production publishing #

  • Developers push local builds only to a development registry, never to production, whatever the tag.
  • Only trusted CI on a protected branch publishes production images. Developer credentials and pull-request jobs get no production push access; protect workflow definitions like code.
  • Make the registry prefix an explicit chart value, such as image.registryPrefix, applied to application and data images alike. Local development selects the development registry with SKAFFOLD_DEFAULT_REPO and never falls back to production; CI selects the production prefix. Pass Skaffold's resolved image references into Helm (image registries).
  • In Skaffold-managed manifests, use the exact build.artifacts[].image name (for example myapp) as the workload image, without a registry; Skaffold replaces only names it builds. Before declaring success, check that the ready Pod runs the digest just built.

Skaffold target #

Keep a .dockerignore at each build-context root.

Skaffold reads its target from SKAFFOLD_KUBE_CONTEXT, SKAFFOLD_NAMESPACE and SKAFFOLD_DEFAULT_REPO, set in the environment or in the project's skaffold.env; the environment wins (env file).

  • Commit skaffold.env.example; developers copy it to a git-ignored skaffold.env with their own context, namespace and registry.
  • Agent workers get these variables from their environment.
  • Run plain skaffold dev, build or run. Never retarget with --kube-context, --namespace, --default-repo, skaffold config set or edits to skaffold.env; if the target is missing or wrong, report it and stop.
# skaffold.env.example
SKAFFOLD_KUBE_CONTEXT=dev-cluster
SKAFFOLD_NAMESPACE=team-dev
SKAFFOLD_DEFAULT_REPO=registry.dev.example.com/team

The build and manifest sections of a multi-service configuration follow. It builds with the local Docker daemon; an in-cluster builder such as Kaniko comes from the target cluster's Driftmower guidance.

lolcatz/skaffold.yaml:

build:
  platforms:
    - linux/amd64
  tagPolicy:
    inputDigest: {}
  # Build on your laptop and push using local Docker registry credentials.
  # Configure your context-specific default-repo and registry login (see README.md).
  # Host networking lets local builds use the host DNS and IPv6 connectivity.
  local:
    concurrency: 0
    push: true
    useDockerCLI: true
    useBuildkit: true
  artifacts:
    - image: lolcatz-uploader
      docker:
        dockerfile: services/Dockerfile.golang
        network: host
        buildArgs:
          SERVICE: uploader
    - image: lolcatz-browse
      docker:
        dockerfile: services/Dockerfile.golang
        network: host
        buildArgs:
          SERVICE: browse
    - image: lolcatz-search
      docker:
        dockerfile: services/Dockerfile.search
        network: host
    - image: lolcatz-comments
      docker:
        dockerfile: services/Dockerfile.golang
        network: host
        buildArgs:
          SERVICE: comments
    - image: lolcatz-thumbnailer
      docker:
        dockerfile: services/Dockerfile.python
        network: host
        target: thumbnailer
    - image: lolcatz-frontend
      docker:
        dockerfile: services/Dockerfile.frontend
        network: host
manifests:
  helm:
    releases:
      - name: lolcatz
        chartPath: chart
        skipTests: true
        setValues:
          imageRegistry: ""
          # Leave room for PostgreSQL in the sandbox memory quota.
          thumbnailerWorker.enabled: false
          exif.enabled: false
          admin.enabled: false
        # Helm test hooks and image volumes are outside automatic image replacement.
        setValueTemplates:
          frontend.image: "{{.IMAGE_FULLY_QUALIFIED_lolcatz_frontend}}"

Reproducible, immutable production artifacts #

  • Build every production image from a recorded commit and declared inputs: committed Dockerfiles, build configuration and lockfiles, with base images and downloads pinned by digest or checksum. Large model or data inputs may live outside Git, but their references, checksums and preparation steps live in Git.
  • CI builds, checks and scans each revision once, runs integration checks through Compose, verifies the image in Kubernetes and promotes that same artifact through staging and production.
  • Set the OCI image annotations (source, revision, created, version, title, description; license only when established) from the same revision as the tag.
  • Production tags are immutable and deployed by digest; latest is for development only. The same applies to data images. Digests reach the chart only at release time (see below).
  • Record each release's source, image digests and configuration so it can be redeployed or rolled back; check schema compatibility before rollback (deploying/workloads).

Multi-architecture images #

  • Publish linux/amd64 and linux/arm64 images under one tag as an image index.
  • Keep Dockerfiles architecture-agnostic: no hardcoded GOARCH, architecture names or TARGETARCH branches. Each stage builds for the machine it runs on. For a pinned upstream binary, pick the file by dpkg --print-architecture and verify it against a committed sha256sum file with one reviewed line per architecture; a missing line fails the build. A checksum fetched at build time proves nothing.
  • Build each architecture natively on its own runner, such as ubuntu-24.04-arm, not under QEMU. Push each build by digest, join them with docker buildx imagetools create and tag only the index.

Example: one Dockerfile download for either architecture, verified against committed checksums. Version the local file name so a version bump also requires a new checksum line.

42b9e2e3246c19b78fcc53dd60cc7ded1da8704293886b909a2a02b9bef34d20  skaffold-v2.25.0-linux-amd64
416f5fed2009c2b4adc62ae887ee5fc19ff08cc8a0250b81d8682d55626a75fd  skaffold-v2.25.0-linux-arm64
COPY checksums.sha256 /tmp/checksums.sha256
RUN set -e; arch="$(dpkg --print-architecture)"; cd /tmp; \
    file="skaffold-v2.25.0-linux-${arch}"; \
    curl -fsSL "https://storage.googleapis.com/skaffold/releases/v2.25.0/skaffold-linux-${arch}" -o "$file"; \
    grep "  $file\$" checksums.sha256 | sha256sum -c -; \
    install -m 0755 "$file" /usr/local/bin/skaffold; rm -rf /tmp/*

Example: GitHub Actions builds per architecture, then merges.

jobs:
  build:
    runs-on: ${{ matrix.runner }}
    strategy:
      matrix:
        include:
          - {arch: amd64, runner: ubuntu-24.04}
          - {arch: arm64, runner: ubuntu-24.04-arm}
    steps:
      - uses: actions/checkout@v7
      - uses: docker/setup-buildx-action@v4
      - uses: docker/login-action@v4
        with: {registry: ghcr.io, username: "${{ github.actor }}", password: "${{ secrets.GITHUB_TOKEN }}"}
      - id: build
        uses: docker/build-push-action@v7
        with:
          platforms: linux/${{ matrix.arch }}
          outputs: type=image,name=ghcr.io/example/app,push-by-digest=true,name-canonical=true,push=true
      - run: mkdir -p digests && echo "${{ steps.build.outputs.digest }}" > "digests/${{ matrix.arch }}"
      - uses: actions/upload-artifact@v7
        with: {name: "digest-${{ matrix.arch }}", path: digests/*}
  merge:
    needs: build
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/download-artifact@v8
        with: {pattern: digest-*, merge-multiple: true, path: digests}
      - uses: docker/setup-buildx-action@v4
      - uses: docker/login-action@v4
        with: {registry: ghcr.io, username: "${{ github.actor }}", password: "${{ secrets.GITHUB_TOKEN }}"}
      - run: |
          docker buildx imagetools create -t ghcr.io/example/app:${{ github.sha }} \
            $(for d in digests/*; do echo "ghcr.io/example/app@$(cat "$d")"; done)

OCI Helm chart releases #

  • Publish images as ghcr.io/<owner>/<app>-<component> and charts as oci://ghcr.io/<owner>/charts/<chart>, unless the project already has a layout.
  • Tag v1.2.3 releases chart version 1.2.3 with appVersion v1.2.3, from the v* release workflow only, after checks and every image index succeed.
  • Never commit image tags or digests to the repository. Committed charts reference images by name only; the release pipeline builds the images and substitutes their digests, including data images, into the chart's templates or values in its own working copy before packaging.
  • helm push takes oci://ghcr.io/<owner>/charts; Helm appends the chart name and version. The lolcatz release workflow is an example of this stamping.

Apply building/general for image and runtime conventions.

  • Copy go.mod and go.sum before sources; run go mod download to cache dependency downloads separately.
  • For Go services that support CGO_ENABLED=0, build a static binary and use FROM scratch for the final stage. CGo applications need compatible runtime libraries or verified static linking. Optional -ldflags="-s -w" removes symbol/debug information.
  • Copy required application assets to their runtime paths and verify the image starts and serves them. CA trust comes from the runtime (building/general).

An example that builds one of several services, selected by a build argument:

lolcatz/services/Dockerfile.golang:

FROM golang:1.26-alpine AS source
WORKDIR /app
COPY services/go.mod services/go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod go mod download
COPY services/internal ./internal
COPY services/admin ./admin
COPY services/browse ./browse
COPY services/comments ./comments
COPY services/exif ./exif
COPY services/uploader ./uploader

# …

FROM source AS build
ARG SERVICE
RUN --mount=type=cache,target=/go/pkg/mod \
    --mount=type=cache,target=/root/.cache/go-build \
    test -n "$SERVICE" && CGO_ENABLED=0 go build -ldflags="-s -w" -o /app/server "./$SERVICE"

FROM scratch AS runtime
COPY --from=build /app/server /server
EXPOSE 8080
ENTRYPOINT ["/server"]

A JVM application cannot run in scratch. Its image carries a full Java runtime, which makes it larger and slower to pull and start than a statically linked binary. See developing/languages/java for the runtime trade-offs to consider before choosing Java for a new application.

For existing Java applications, apply building/general for shared image conventions.

  • Declare the Java version in build configuration and align builder and runtime versions. Choose a maintained distribution, for example Temurin or Corretto.
  • Size the heap relative to the container memory limit, for example with -XX:MaxRAMPercentage, rather than with a fixed -Xmx. Leave headroom for off-heap memory such as metaspace, thread stacks and direct buffers.
  • Match the copied artifact filename to the file the build tool actually produces.

Apply building/general for image stages, locked dependencies, runtime identity and process ownership.

  • Use the same pinned Node version across stages. Omit development-only packages from the runtime image.
  • Launch Node directly, as CMD ["node", "server.js"] with the real entrypoint, not through npm start, npm run or npx. Package scripts remain fine for builds, checks and development.

A Next.js example:

lolcatz/services/Dockerfile.frontend:

FROM node:26-alpine AS deps
WORKDIR /app
COPY services/frontend/package.json services/frontend/package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --prefer-offline

# …

FROM node:26-alpine AS builder
WORKDIR /app
ARG NEXT_PUBLIC_DEV_AUTH_TOKEN
ENV NEXT_PUBLIC_DEV_AUTH_TOKEN=$NEXT_PUBLIC_DEV_AUTH_TOKEN
COPY --from=deps /app/node_modules ./node_modules
COPY services/frontend/ .
RUN npm run build && chmod -R a+rX /app/.next /app/public

FROM node:26-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/required-server-files.json ./.next/required-server-files.json
COPY services/frontend/runtime.cjs services/frontend/metrics.cjs ./
# The custom runtime is outside Next.js output tracing.
COPY --from=deps /app/node_modules/prom-client ./node_modules/prom-client
COPY --from=deps /app/node_modules/@opentelemetry ./node_modules/@opentelemetry
COPY --from=deps /app/node_modules/tdigest ./node_modules/tdigest
COPY --from=deps /app/node_modules/bintrees ./node_modules/bintrees
EXPOSE 3000
CMD ["node", "runtime.cjs"]

Apply building/general. Install into the image's Python environment, without a virtual environment; with uv, set UV_PROJECT_ENVIRONMENT=/usr/local.

An example with shared hashed dependencies and a per-service target:

lolcatz/services/Dockerfile.python:

FROM python:3.12-slim AS worker-deps
ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1
WORKDIR /app

# Share the identical locked dependencies without forcing a common Pillow or
# urllib3 version. Each service completes and validates its own dependency graph.
COPY services/worker-requirements.lock ./
RUN --mount=type=cache,target=/root/.cache/pip \
    pip install --require-hashes --no-deps -r worker-requirements.lock

FROM worker-deps AS thumbnailer-deps
COPY services/thumbnailer/requirements.txt services/thumbnailer/requirements.lock ./
RUN --mount=type=cache,target=/root/.cache/pip \
    pip install --require-hashes -r requirements.lock \
    && pip install --no-index --no-deps -r requirements.txt \
    && pip check \
    && python -c 'from PIL import features; assert features.check_feature("libjpeg_turbo")'

# …

# The default target is the lightweight service used by the default Skaffold profile.
FROM thumbnailer-deps AS thumbnailer
COPY services/worker_runtime.py services/metrics.py ./
COPY --chmod=0644 services/thumbnailer/server.py services/thumbnailer/app.py services/thumbnailer/cache.py services/thumbnailer/thumbnail.py services/thumbnailer/worker.py ./
EXPOSE 8080
CMD ["python", "server.py"]

Apply building/general for image stages, runtime identity and file permissions.

  • Cache dependencies with the Cargo manifests and committed lockfile, including workspace member manifests: cargo fetch --locked, then cargo build --release --locked. Never update dependencies during an image build.
  • When caching with placeholder sources, replace them with the real source tree so Cargo rebuilds it. Exclude host target directories.
  • A musl build without dynamic libraries runs FROM scratch; otherwise use a minimal runtime with the needed libraries.
  • Copy required application assets and verify the image starts. CA trust comes from the runtime (building/general).

An example:

lolcatz/services/Dockerfile.search:

FROM rust:1.94.1-alpine AS source
RUN apk add --no-cache musl-dev
WORKDIR /app
COPY services/search/Cargo.toml services/search/Cargo.lock ./
# Cargo needs a target to parse the manifest, but fetching only depends on locks.
RUN --mount=type=cache,target=/usr/local/cargo/registry/cache,sharing=locked \
    mkdir src && touch src/main.rs \
    && cargo fetch --locked --target "$(rustc -vV | sed -n 's/^host: //p')"
COPY services/search/src ./src
COPY services/search/tests ./tests
COPY services/search/Rocket.toml ./
# Integration tests use the complete core schema.
COPY services/uploader/schema.sql /schemas/uploader.sql

# …

FROM source AS build
RUN --mount=type=cache,target=/usr/local/cargo/registry/cache,sharing=locked \
    cargo build --locked --release

FROM scratch AS runtime
ENV ROCKET_CONFIG=/app/Rocket.toml
COPY services/search/Rocket.toml /app/Rocket.toml
COPY --from=build /app/target/release/lolcatz-search /server
EXPOSE 8080 9090
ENTRYPOINT ["/server"]

The guide

Deploying

Back to contents ↑

Discover the target with deploying/discovery, choose dependencies with deploying/storage and deploy immutable releases as described in building/ci. Keep configuration in version control, without credentials.

Release ownership and isolation #

  • The platform owns namespaces. Never put kind: Namespace in an application chart, manifest or GitOps inventory. To remove an existing one, first detach it from the release or GitOps inventory so pruning cannot delete the namespace; never delete and recreate it.
  • Applications support several releases per namespace and across namespaces: derive every owned name from .Release.Name through chart helpers, and include the release in Pod labels and selectors. This covers Secrets, ConfigMaps, PVCs, dependency requests and identity registrations.
  • Infrastructure components may instead be singletons with fixed names; document that in the project instructions.
  • Omit metadata.namespace; use .Release.Namespace only where a reference needs it, such as a RoleBinding subject. Hostnames come from values.

Helm values and admission defaults #

  • Expose TLS, trust, listeners, storage classes, replicas and security settings as values with no default. Render a field only when it is set; never copy a platform default with Helm's default.
  • Admission policies may supply IPv6 listeners, database TLS, CA mounts and trust paths, security contexts, storage classes and ingress conventions. Discover each one (deploying/discovery) and pass the setting through values when no policy supplies it. A mounted CA bundle still has to be used by the client.
  • Unset means omitted: no nulls, empty strings or placeholder collections. Test key presence so explicit false and 0 survive.
  • Detect optional APIs per kind with Helm capability checks, not feature flags. Required dependencies are resolved, never silently left out.
  • Render the chart, run a server-side dry run, then verify the admitted resources and readiness.

Environment and rollouts #

  • Write one explicit env: entry per variable, with quoted string values; no envFrom. Reference Secrets and ConfigMaps with secretKeyRef/configMapKeyRef; never inline credentials.
  • Changing only referenced Secret or ConfigMap data does not roll Pods: add a checksum annotation for chart-owned data, or use the owning operator's reload mechanism.
  • Omit unset variables, and env itself when empty.
env:
  - name: LOG_LEVEL
    value: "debug"
  - name: TLS_ENABLED
    value: "true"

Verify release isolation #

Render two releases in one namespace and one release name in two namespaces. Check that names, selectors, RBAC and cluster-scoped resources do not collide; cluster-scoped names need both release and namespace. Also check names the application creates at runtime, such as Jobs, Leases, token audiences, callbacks and service addresses, and pass the release identity to it where needed.

Inspect the target cluster before provisioning. Examples here never establish that an API exists; CRD-specific examples belong to the target cluster's advisory.

The target is SKAFFOLD_KUBE_CONTEXT and SKAFFOLD_NAMESPACE from the environment, else the project's skaffold.env (see building/ci). Use that context and namespace for every kubectl call. Never rely on the current kubeconfig context, and never create or rename contexts to match another machine's skaffold.env. If the target is unclear, ask.

With Driftmower MCP #

Confirm the connection's cluster with get_cluster_identity and its platform (k3s, vanilla, EKS, AKS) with get_cluster_platform; ask when the evidence is unclear. Before using local kubectl, match its API URL to that cluster. Use only the tools the connection advertises:

Information Tool
Platform and version get_cluster_platform
CRDs, served versions, ingress classes, issuers describe_cluster_capabilities
One CRD's schema and description describe_custom_resource_definition
Admission policies and bindings list_admission_policies
StorageClasses list_storage_classes
Namespaces and cluster guidance list_accessible_namespaces, get_cluster_advisory

A listed capability does not prove a healthy controller, create permission or that a policy applies; read the matching policy and binding with kubectl when the summary is not enough. Missing or forbidden information is unknown, not absent.

With kubectl #

Use an explicit, verified --context and an existing namespace; never print kubeconfig credentials.

kubectl --context verified-context api-resources
kubectl --context verified-context version -o yaml
kubectl --context verified-context get storageclasses -o yaml
kubectl --context verified-context --namespace existing-namespace get resourcequotas,limitranges -o yaml

Read StorageClass descriptions and annotations; do not assume a default class. Do not infer the platform from a context or MCP registration name.

Resolve dependency and Prometheus choices through deploying/storage and deploying/observability, recorded as described in developing/general.

Required CRDs #

For each operator API the application uses:

kubectl --context verified-context get crd resourceplural.operator.example -o yaml
kubectl --context verified-context explain resourceplural.spec --api-version=operator.example/v1
kubectl --context verified-context --namespace existing-namespace auth can-i create resourceplural.operator.example

Also check that its controller runs and reconciles in the namespace. If an API or controller is missing, settle how it will be provided before deploying; never install an operator or copy CRDs into the application chart. Distinguish Forbidden, network failures and NotFound.

Admission #
kubectl --context verified-context api-resources --api-group=admissionregistration.k8s.io
kubectl --context verified-context get validatingadmissionpolicies,validatingadmissionpolicybindings -o yaml
kubectl --context verified-context get mutatingadmissionpolicies,mutatingadmissionpolicybindings -o yaml

Query only the kinds the first command lists, and webhook configurations too. Match each policy to its binding's resources, operations, selectors and parameters; an unbound policy supplies nothing. If inspection is forbidden, ask for the requirements instead of assuming none.

TLS and trust #

If cert-manager is installed, read the issuers and their readiness:

kubectl --context verified-context get clusterissuers -o yaml
kubectl --context verified-context --namespace existing-namespace get issuers -o yaml

If trust-manager is installed, find the Bundle that targets the namespace and confirm its data exists there; Pod mounts come from mutation policies, not the bundle. Read Secret key names only, never values. Shared trust resources stay platform-owned (deploying/storage).

Then apply deploying/general.

  • Address services by name in Compose and by namespace-qualified name in Kubernetes. Keep Service selectors, target ports and listeners aligned; hostnames come from deployment values.
  • In Kubernetes, listen on :: with IPv4 accepted, or on both families; 0.0.0.0 is IPv4 only. Compose may stay IPv4.
  • Give inter-service calls timeouts; retry only repeatable operations, with backoff and a finite budget.
  • TLS is a runtime setting: off in Compose, verified TLS for every Kubernetes connection. Certificates and trust paths never go in images. Metrics transport is decided separately (deploying/observability).
  • Find issuers, allowed hostnames and trust bundles with deploying/discovery and reuse an existing issuer that fits. With cert-manager and trust-manager installed, admission policies usually mount the namespace trust bundle into Pods; otherwise configure the mount through values.
  • Servers load their certificates; clients trust the issuer and verify hostnames, and reload or restart after renewal. TLS does not replace authentication.
  • Expose browser routes through Ingress, with certificate names, Ingress hosts, public URLs and OIDC redirect URIs agreeing. Workers and admin endpoints stay internal; health and metrics use the internal listener (developing/metrics).
  • Write NetworkPolicy so the Ingress controller reaches only the application port and Prometheus only the metrics port, one rule per caller with its namespace and Pod labels; a rule combining both callers and both ports grants each both. Policies match Pod ports, not Service ports, and allow rules add up across policies. Account for health probes.

Metrics drive alerts, logs drive triage and traces locate latency across services. Use the platform's tracing pipeline when it has one, configurably, without credentials or sensitive payloads. Instrumentation: developing/metrics, developing/health-checks, developing/logging.

Prometheus transport decision #

Before configuring scraping, ask the user to choose internal HTTP (unencrypted) or HTTPS (certificates, trust and renewal), and record it (developing/general). Do not derive it from the application's TLS setting, and do not fall back to HTTP when certificates are missing.

Monitoring integration #

  • Use the installed monitoring stack; with Prometheus Operator, follow the cluster's guidance. Never install monitoring from the application chart.
  • Scrape the named container metrics port with a PodMonitor in the workload's namespace, without a metrics Service or ServiceMonitor. Check that Prometheus selects the PodMonitor and the PodMonitor selects the release's Pods.
  • Render PodMonitor and PrometheusRule only when Helm capabilities show monitoring.coreos.com/v1; metrics stay served either way.
  • Then verify that scraping succeeds. Probes use the internal listener; logs go to stdout and stderr.
  • Run as a non-root identity supplied by platform policy or deployment values, with a read-only root filesystem and explicit writable mounts. Keep identity and Pod security as unset chart values (deploying/general). If no policy sets seccomp, set seccompProfile.type: RuntimeDefault on the Pod.
  • Credentials never go in source, images or logs. Commit generator or secret-store declarations, never generated values; consume Secrets by explicit reference or mounted file. Locally, use untracked configuration.
  • Required Secrets and ConfigMaps are never optional: true: let the Pod wait for the provisioner. Reject missing or empty required values at startup.
  • Rotate without rebuilding: give each component relationship its own credential, roll out the replacement to every consumer, verify, then revoke the old one. Reuse operator-generated credentials where the operator owns authentication. Document and exercise the procedure.
  • Provision OIDC clients through the identity service (developing/architecture, deploying/storage) with matching issuer, audience and HTTPS redirect URIs; confidential client secrets stay server-side.
  • Provision session-signing secrets once, share them across replicas and rotate them deliberately, not on every deploy.

Native or portable services #

After identifying the platform (deploying/discovery), ask the user to choose provider-native managed services or portable Kubernetes operators, and record the choice (developing/general). For PostgreSQL on AWS that is Amazon RDS against CloudNativePG: provider operations against owning operator, storage, backup and recovery. Check availability, permissions and cost first; if a prerequisite is missing, resolve it with the user rather than switching approach.

Ownership and provisioning #

  • Request databases, caches and OIDC registrations as custom resources, for example CloudNativePG, Dragonfly Operator and Passmower, when discovery shows them. Native services go through a provisioning API such as Crossplane.
  • The platform team runs the operators and identity services, with their upgrades, backups and recovery; the application release owns only its own requests and registrations. Never install shared operators or dependency charts from the application chart, and never handwrite StatefulSets for backing services.
  • Keep each instance's requests, registrations and credential references in the application's namespace, even for a remote service.
  • Each release gets its own databases, cache access and registrations (deploying/general); sharing is an explicit recorded choice. Credential rotation: deploying/security.

Data lifecycle #

  • Containers are stateless: keep cross-request session state in a backing service or a client-side session, never in replica memory or sticky routing. Choose storage class, retention, backups and restore for each store and test recovery; a retained PVC is not a backup. Temporary files go on bounded disposable volumes.
  • Configure internal and browser-facing object-storage endpoints separately (developing/architecture, deploying/networking).
  • Custom-resource schemas and examples come from the target cluster's Driftmower advisory or the operator's documentation.
  • Run HTTP servers and background workers as separate workloads so they scale and are sized independently; they may share an image with different commands. Workers without inbound traffic need no Service.
  • Do not build an orchestrator inside a container: no forked worker managers, supervisord or s6 trees, embedded brokers dispatching child workers or custom restart loops. Use Kubernetes workloads, and a separately provisioned queue for durable messaging. Bounded in-process tasks are fine.
  • Use a Lease for leader election, a CronJob for schedules and a Job for finite work.
  • Ship migrations and maintenance commands in the application image and run them as Jobs with the release's configuration, so replicas never race. Support two application versions overlapping during a rollout.
  • Set the termination grace period to cover draining, and Job retry and concurrency limits to match the work's duplicate-delivery semantics.
  • Size CPU and memory per component within the namespace quota (deploying/discovery).
  • Discover messaging APIs before declaring topics, and choose partitions, retention and replay deliberately; a compacted topic keeps only the latest value per key.
  • Large images cost a pull on a new node; never trade that for installing dependencies at startup.

Mount packaged data with image volumes #

Mount the data images from building/general as read-only image volumes, with the reference (a digest in production) and mount path in deployment values. Keep writable output on separate storage. If the cluster lacks image-volume support, agree on another delivery mechanism, never by baking the data back into the application image.

For your coding agent

The same guide, over MCP.

Connect using Streamable HTTP. No sign-in or API key is required. Choose project scope to share setup with a repository, or user scope to use it across projects.

https://mcp.codemowers.io/mcp

Codex

Global · your user account

This command adds the server to your user configuration, normally ~/.codex/config.toml:

codex mcp add codemowers --url https://mcp.codemowers.io/mcp

Project · this repository

Add this table to .codex/config.toml in the project root, preserving existing settings. Codex loads project configuration for trusted projects.

[mcp_servers.codemowers]
url = "https://mcp.codemowers.io/mcp"

Codex MCP documentation ↗

Claude Code

Global · your user account

claude mcp add --transport http --scope user codemowers https://mcp.codemowers.io/mcp

Project · this repository

Run from the project root. This creates or updates .mcp.json, which can be committed for the team. Claude Code prompts before using project-scoped servers.

claude mcp add --transport http --scope project codemowers https://mcp.codemowers.io/mcp

Claude Code MCP documentation ↗

OpenCode

Global · your user account

opencode mcp add codemowers --global --url https://mcp.codemowers.io/mcp

For manual setup, merge the configuration below into ~/.config/opencode/opencode.json, preserving existing settings and MCP servers.

Project · this repository

Run from the project root:

opencode mcp add codemowers --url https://mcp.codemowers.io/mcp

For manual project setup, merge the same configuration into opencode.json in the project root. This file can be committed for the team. Both locations also support opencode.jsonc.

The commands above require OpenCode V2. Alternatively, merge this V2 configuration by hand:

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "servers": {
      "codemowers": {
        "type": "remote",
        "url": "https://mcp.codemowers.io/mcp"
      }
    }
  }
}
OpenCode V1 configuration

V1 places server names directly under mcp:

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "codemowers": {
      "type": "remote",
      "url": "https://mcp.codemowers.io/mcp"
    }
  }
}

OpenCode MCP documentation ↗

Run locally with Docker

Once an image is published, replace VERSION with its published tag, or use an image digest:

docker run --rm --name codemowers-mcp \
  -p 127.0.0.1:3000:3000 \
  -e PUBLIC_URL=http://localhost:3000 \
  ghcr.io/codemowers/codemowers-mcp:VERSION

Open localhost:3000 ↗ for the guide. For local MCP access, substitute http://localhost:3000/mcp in the setup snippets above. Stop the container with Ctrl-C.

Call get_engineering_advisory without arguments for the index, or supply a document path. Documents are also available as MCP resources. Discover the target cluster’s capabilities and policies before provisioning.