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.
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 buildnames 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-daemonstops 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 testskips tests during the image build. Run them in CI before building; the image build should only package.bootJarproduces just the executable jar (the plainjartask isn’t run), sobuild/libs/*.jarmatches exactly one file.- The toolchain still works. Our
build.gradle.ktsasks 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 10001runs the app as an unprivileged user. We use a number rather than the nameappfor a Kubernetes reason explained below.-XX:MaxRAMPercentage=75sizes 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.
depsonly rerunsnpm ciwhenpackage.jsonor the lock file changes, which is the same caching trick as the Gradle build. npm ci, notnpm 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) andpublic/have to be copied next to it, or the page loads without styles. HOSTNAME=0.0.0.0makes 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_URLis 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.
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
appsand PostgreSQL is indata, so it uses the full name<service>.<namespace>.svc.cluster.local. The frontend and backend share a namespace, sohttp://backend:8080is enough. envFromwithsecretRefturns every key in the Secret into an environment variable, which matches the${JWT_SECRET}and${DB_PASSWORD}placeholders inapplication.ymlfrom part 4.runAsNonRoot: truemakes the kubelet refuse to start a container that would run as root. It can only check a numeric user, which is why the Dockerfiles sayUSER 10001andUSER 1001. WithUSER appthe pod fails withCreateContainerConfigErrorbecause the kubelet can’t verify the name isn’t root.- The memory limit is what
MaxRAMPercentage=75reads, 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
- Apply the manifests
kubectl apply -f k8s/raw/data.yml -f k8s/raw/apps.yml - Watch the pods start
kubectl get pods -n dataandkubectl get pods -n apps -w. The backend may restart once if it starts before PostgreSQL is accepting connections. - Follow the backend log
kubectl logs -n apps deploy/backend -fshows Flyway applyingV1, and later the MFA code. - Open the frontend
kubectl port-forward -n apps svc/frontend 3000:3000, then visithttp://localhost:3000/registerand 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.
kubectl apply has no idea what the previous version was, so there's no single command to roll back.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: truecan actually verify it. eval $(minikube docker-env)builds images inside the node, with no registry; use version tags, neverlatest.- 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.
Comments
No comments yet. Be the first to say something.