Tech Notes

Series Kubernetes & Helm from scratch · Part 6

Containerising both apps

Package the Spring Boot backend and Next.js frontend as small, non-root images with multi-stage Dockerfiles, build them into Minikube and run them as raw manifests.

We now have two working apps on the laptop: the Spring Boot API from part 4 and the Next.js frontend from part 5. Kubernetes doesn’t run source code or Gradle tasks, though. It runs container images. So in this part we write a Dockerfile for each app, build the images straight into Minikube, and deploy everything with plain YAML manifests.

The goal is images that are small, rebuild quickly when only the code changes, and don’t run as root. By the end we’ll also have felt why hand-written manifests stop being pleasant, which is exactly the problem Helm solves in the next few parts.

Multi-stage builds in one picture

Both Dockerfiles use the same idea. A builder stage has everything needed to compile: a full JDK, Gradle, node_modules, the source. A runtime stage starts from a much smaller base image and copies in only the finished artefact. The builder stage is thrown away, so none of the build tooling ships.

A builder stage containing the JDK, Gradle, dependencies and source produces a jar; only that jar is copied into a small JRE runtime stage, and the builder stage is discarded. Stage 1 · buildereclipse-temurin:21-jdk-alpine gradlew + build.gradle.kts dependencies (cached layer) src/ → bootJar app.jar COPY --from=build Stage 2 · runtimeeclipse-temurin:21-jre-alpineapp.jarUSER 10001
Only the arrow crosses between stages. The JDK, Gradle caches and source code never reach the image that runs in the cluster.

The backend Dockerfile

apps/backend/Dockerfile:

# ---- Stage 1: build the jar ----
FROM eclipse-temurin:21-jdk-alpine AS build
WORKDIR /workspace

# 1. Build files first: this layer only changes when dependencies change
COPY gradlew settings.gradle.kts build.gradle.kts ./
COPY gradle gradle
RUN ./gradlew dependencies --no-daemon > /dev/null

# 2. Source last: editing code doesn't invalidate the dependency layer
COPY src src
RUN ./gradlew bootJar --no-daemon -x test \
 && cp build/libs/*.jar app.jar

# ---- Stage 2: run it ----
FROM eclipse-temurin:21-jre-alpine
WORKDIR /app

RUN addgroup -S -g 10001 app && adduser -S -u 10001 -G app app
COPY --from=build --chown=10001:10001 /workspace/app.jar app.jar
USER 10001

EXPOSE 8080
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "/app/app.jar"]

Line by line, the parts that matter:

  • AS build names the first stage so the second can copy from it.
  • The copy order is the caching strategy. Docker reuses a layer until one of the files copied into it changes. Wrapper and build scripts change rarely, so ./gradlew dependencies (which downloads every library) stays cached. Source code changes all the time, so it’s copied last and only the final compile reruns.
  • --no-daemon stops Gradle starting its background daemon. A daemon speeds up repeated builds on a laptop, but in a one-shot container build it only costs memory and start-up time.
  • -x test skips tests during the image build. Run them in CI before building; the image build should only package.
  • bootJar produces just the executable jar (the plain jar task isn’t run), so build/libs/*.jar matches exactly one file.
  • The toolchain still works. Our build.gradle.kts asks for a Java 21 toolchain, and the builder image already provides JDK 21, so Gradle uses it instead of downloading another.
  • A JRE, not a JDK, at runtime. The runtime only needs to run bytecode, not compile it.
  • USER 10001 runs the app as an unprivileged user. We use a number rather than the name app for a Kubernetes reason explained below.
  • -XX:MaxRAMPercentage=75 sizes the heap from the container’s memory limit rather than the node’s memory. We’ll tune this properly in part 9.

Add apps/backend/.dockerignore so the build context stays small and local build output never leaks in:

build/
.gradle/
.idea/
*.iml

The frontend Dockerfile

Next.js can produce a standalone build: a minimal server.js plus only the node_modules files the app actually imports. Turn it on in apps/frontend/next.config.ts:

import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  output: "standalone",
};

export default nextConfig;

apps/frontend/Dockerfile:

# ---- Stage 1: install dependencies ----
FROM node:22-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci

# ---- Stage 2: build ----
FROM node:22-alpine AS build
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ENV NEXT_TELEMETRY_DISABLED=1
RUN npm run build

# ---- Stage 3: run ----
FROM node:22-alpine
WORKDIR /app
ENV NODE_ENV=production NEXT_TELEMETRY_DISABLED=1 PORT=3000 HOSTNAME=0.0.0.0

RUN addgroup -S -g 1001 nextjs && adduser -S -u 1001 -G nextjs nextjs
COPY --from=build --chown=1001:1001 /app/.next/standalone ./
COPY --from=build --chown=1001:1001 /app/.next/static ./.next/static
COPY --from=build --chown=1001:1001 /app/public ./public
USER 1001

EXPOSE 3000
CMD ["node", "server.js"]

What to notice:

  • Three stages. deps only reruns npm ci when package.json or the lock file changes, which is the same caching trick as the Gradle build.
  • npm ci, not npm install: it installs exactly what the lock file says and fails if the two disagree.
  • The standalone output doesn’t include static assets. .next/static (the hashed JS and CSS bundles) and public/ have to be copied next to it, or the page loads without styles.
  • HOSTNAME=0.0.0.0 makes the server listen on every interface. Without it, it can bind only to the container’s own hostname, and a port-forward or Service can’t reach it.
  • BACKEND_URL is not set here. As we planned in part 5, it’s read at runtime, so the same image works in every environment; the Deployment supplies it.

apps/frontend/.dockerignore:

node_modules
.next
.env*.local

That last line matters: .env.local points at localhost:8080, which is wrong inside a cluster and shouldn’t be baked into any image.

Build straight into Minikube

Minikube runs its own Docker daemon inside the node. If we point our docker CLI at that daemon, images we build are already where the kubelet looks for them. No registry, no push.

After eval minikube docker-env, the docker CLI on the laptop sends builds to the Docker daemon inside the Minikube node, where the kubelet finds the images locally without pulling from a registry. Your Macdocker buildDOCKER_HOST →Minikube's daemon Minikube nodeDocker daemonauth-backend:0.1.0kubeletIfNotPresent Pod
The image never leaves the node: built by its daemon, found there by the kubelet, run as a pod.

From the repository root, with Minikube running:

eval $(minikube docker-env)

docker build -t auth-backend:0.1.0 apps/backend
docker build -t auth-frontend:0.1.0 apps/frontend

docker images | grep auth-

minikube docker-env prints a few export lines (DOCKER_HOST, TLS settings and so on); eval applies them to the current shell only. Open a new terminal and you’re back on your normal Docker. To switch back in the same shell, run eval $(minikube docker-env -u).

Because the Minikube node runs natively on Apple Silicon, the images are built for arm64 and match the node, with no cross-platform flags needed.

Gotcha: don't tag these images latest. For a :latest tag Kubernetes defaults imagePullPolicy to Always, tries to pull auth-backend from Docker Hub, and the pod sits in ErrImagePull. With a version tag the default is IfNotPresent, which finds the local image.

Run everything as raw manifests

The backend needs PostgreSQL and Redis. We’ll install proper, persistent versions with Helm in parts 7 and 8; for now a throwaway Deployment and Service for each in the data namespace is enough to prove the images work. k8s/raw/data.yml:

apiVersion: apps/v1
kind: Deployment
metadata: { name: postgres, namespace: data }
spec:
  selector: { matchLabels: { app: postgres } }
  template:
    metadata: { labels: { app: postgres } }
    spec:
      containers:
        - name: postgres
          image: postgres:16
          env:
            - { name: POSTGRES_DB, value: auth }
            - { name: POSTGRES_USER, value: auth }
            - { name: POSTGRES_PASSWORD, value: auth }   # throwaway, replaced in part 7
          ports: [{ containerPort: 5432 }]
---
apiVersion: v1
kind: Service
metadata: { name: postgres, namespace: data }
spec:
  selector: { app: postgres }
  ports: [{ port: 5432 }]
---
apiVersion: apps/v1
kind: Deployment
metadata: { name: redis, namespace: data }
spec:
  selector: { matchLabels: { app: redis } }
  template:
    metadata: { labels: { app: redis } }
    spec:
      containers:
        - name: redis
          image: redis:7
          ports: [{ containerPort: 6379 }]
---
apiVersion: v1
kind: Service
metadata: { name: redis, namespace: data }
spec:
  selector: { app: redis }
  ports: [{ port: 6379 }]

There’s no volume, so the data disappears with the pod. That’s fine for a smoke test and is exactly what part 7 fixes.

The JWT secret shouldn’t live in a file we commit, so create it from the command line:

kubectl create secret generic backend-secrets -n apps \
  --from-literal=JWT_SECRET="$(openssl rand -base64 48)" \
  --from-literal=DB_PASSWORD=auth

Now k8s/raw/apps.yml:

apiVersion: apps/v1
kind: Deployment
metadata: { name: backend, namespace: apps }
spec:
  selector: { matchLabels: { app: backend } }
  template:
    metadata: { labels: { app: backend } }
    spec:
      securityContext: { runAsNonRoot: true }
      containers:
        - name: backend
          image: auth-backend:0.1.0
          ports: [{ containerPort: 8080 }]
          env:
            - { name: DB_URL, value: "jdbc:postgresql://postgres.data.svc.cluster.local:5432/auth" }
            - { name: DB_USERNAME, value: auth }
            - { name: REDIS_HOST, value: redis.data.svc.cluster.local }
          envFrom:
            - secretRef: { name: backend-secrets }   # JWT_SECRET and DB_PASSWORD
          resources:
            requests: { cpu: 250m, memory: 512Mi }
            limits: { memory: 768Mi }
---
apiVersion: v1
kind: Service
metadata: { name: backend, namespace: apps }
spec:
  selector: { app: backend }
  ports: [{ port: 8080 }]
---
apiVersion: apps/v1
kind: Deployment
metadata: { name: frontend, namespace: apps }
spec:
  selector: { matchLabels: { app: frontend } }
  template:
    metadata: { labels: { app: frontend } }
    spec:
      securityContext: { runAsNonRoot: true }
      containers:
        - name: frontend
          image: auth-frontend:0.1.0
          ports: [{ containerPort: 3000 }]
          env:
            - { name: BACKEND_URL, value: "http://backend:8080" }
          resources:
            requests: { cpu: 100m, memory: 128Mi }
            limits: { memory: 256Mi }
---
apiVersion: v1
kind: Service
metadata: { name: frontend, namespace: apps }
spec:
  selector: { app: frontend }
  ports: [{ port: 3000 }]

The interesting lines:

  • Cross-namespace DNS. The backend is in apps and PostgreSQL is in data, so it uses the full name <service>.<namespace>.svc.cluster.local. The frontend and backend share a namespace, so http://backend:8080 is enough.
  • envFrom with secretRef turns every key in the Secret into an environment variable, which matches the ${JWT_SECRET} and ${DB_PASSWORD} placeholders in application.yml from part 4.
  • runAsNonRoot: true makes the kubelet refuse to start a container that would run as root. It can only check a numeric user, which is why the Dockerfiles say USER 10001 and USER 1001. With USER app the pod fails with CreateContainerConfigError because the kubelet can’t verify the name isn’t root.
  • The memory limit is what MaxRAMPercentage=75 reads, so the JVM heap is about 576 MiB, leaving room for the rest of the JVM. Probes are left out on purpose; they arrive with the Helm chart in part 9.

Deploy and test

  1. Apply the manifests kubectl apply -f k8s/raw/data.yml -f k8s/raw/apps.yml
  2. Watch the pods start kubectl get pods -n data and kubectl get pods -n apps -w. The backend may restart once if it starts before PostgreSQL is accepting connections.
  3. Follow the backend log kubectl logs -n apps deploy/backend -f shows Flyway applying V1, and later the MFA code.
  4. Open the frontend kubectl port-forward -n apps svc/frontend 3000:3000, then visit http://localhost:3000/register and walk through register → log in → code → dashboard.

The flow is the same one we tested in part 5, but now every hop is a pod talking to a Service. Only the frontend is reachable from the laptop; the backend isn’t exposed at all.

Because the frontend image runs with NODE_ENV=production, its cookies are marked Secure. Browsers treat http://localhost as a secure context, so this works through port-forward; we’ll put proper HTTPS in front of it with Ingress later.

When something doesn’t start, these three commands find most problems:

kubectl describe pod -n apps -l app=backend   # events: image pull, config and scheduling errors
kubectl logs -n apps deploy/backend --previous # output of the container before its last restart
kubectl get events -n apps --sort-by=.lastTimestamp

After a code change, rebuild with a new tag (0.1.1), update the image: line and apply again. Reusing the same tag works with kubectl rollout restart, but it makes it impossible to tell which build a pod is running.

Why raw YAML stops scaling

It works, but look at what we’ve written. Two Deployments and two Services that are nearly identical. Image tags that have to be edited by hand. Values such as the backend Service name repeated in several places. And this is only one environment.

Copy and paste Every app repeats the same Deployment, Service, labels and security settings, and they drift apart.
One file per environment Dev, staging and production need different replicas, resources and hosts, so the whole file gets copied three times.
No release history kubectl apply has no idea what the previous version was, so there's no single command to roll back.
No packaged dependencies A proper PostgreSQL needs a StatefulSet, PVCs, Secrets and more; nobody wants to hand-write that.

Helm fixes all four: templates instead of copies, a small values file per environment, numbered releases with helm rollback, and ready-made charts for databases. We’ll start with that last one. Clean up the throwaway data services first:

kubectl delete -f k8s/raw/data.yml

Keep the images and the backend-secrets Secret; we’ll reuse them.

Takeaways

  • Multi-stage builds keep compilers, caches and source out of the runtime image: JDK to build, JRE to run; full Node to build, standalone output to run.
  • Copy dependency manifests before source code so the slow dependency download stays cached.
  • Run as a numeric non-root user so runAsNonRoot: true can actually verify it.
  • eval $(minikube docker-env) builds images inside the node, with no registry; use version tags, never latest.
  • Cross-namespace calls use <service>.<namespace>.svc.cluster.local; same-namespace calls can use the short name.
  • Raw manifests work, but repetition, per-environment copies and the lack of rollbacks are what Helm is for.

Next, in part 7, we install PostgreSQL properly with the Bitnami Helm chart, with an existing Secret and persistent storage.