3.1. Implementation

In this lab, you build the images of the message board, run PostgreSQL in your cluster and connect the frontend and the backend to it.

Step 1: Build the Images

Create the directories for the files of this lab and change into the main directory:

mkdir -p ~/labs/3.1/backend ~/labs/3.1/frontend
cd ~/labs/3.1

Create the three files of the backend in ~/labs/3.1/backend. main.py contains the application:

import os
import socket
from contextlib import asynccontextmanager

import psycopg
from fastapi import FastAPI
from pydantic import BaseModel


def connect():
    return psycopg.connect(
        host=os.environ["POSTGRES_HOST"],
        dbname=os.environ["POSTGRES_DB"],
        user=os.environ["POSTGRES_USER"],
        password=os.environ["POSTGRES_PASSWORD"]
    )


@asynccontextmanager
async def lifespan(app):
    with connect() as conn:
        conn.execute(
            """
            create table if not exists messages (
                id serial primary key,
                created_at timestamptz not null default now(),
                text text not null
            )
            """
        )
    yield


app = FastAPI(lifespan=lifespan)


class MessageInput(BaseModel):
    text: str


@app.get("/health")
def health():
    with connect() as conn:
        conn.execute("select 1")
    return {"status": "ok", "pod": socket.gethostname()}


@app.get("/messages")
def list_messages():
    with connect() as conn:
        rows = conn.execute("select id, created_at, text from messages order by created_at desc").fetchall()
    return [
        {"id": id, "created_at": created_at.isoformat(), "text": text}
        for id, created_at, text in rows
    ]


@app.post("/messages")
def create_message(message: MessageInput):
    with connect() as conn:
        conn.execute("insert into messages (text) values (%s)", (message.text,))
    return {"status": "ok"}

requirements.txt lists the Python packages it needs:

fastapi==0.143.0
uvicorn==0.54.0
psycopg[binary]==3.3.6

Dockerfile describes how to build its image:

FROM python:3.14-slim
COPY --from=ghcr.io/astral-sh/uv:0.13.0 /uv /bin/uv
WORKDIR /app
COPY requirements.txt .
RUN uv pip install --system --no-cache -r requirements.txt
COPY main.py .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Create the three files of the frontend in ~/labs/3.1/frontend. index.html is the web page:

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Message Board</title>
</head>
<body>
  <h1>Message Board</h1>
  <input id="text" placeholder="Your message">
  <button onclick="submitText()">Submit</button>
  <ul id="items"></ul>

  <script>
    async function load() {
      const res = await fetch('/api/messages');
      const messages = await res.json();
      items.replaceChildren(...messages.map(m => {
        const li = document.createElement('li');
        li.textContent = `${new Date(m.created_at).toLocaleString()}: ${m.text}`;
        return li;
      }));
    }

    async function submitText() {
      await fetch('/api/messages', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({text: text.value})
      });
      text.value = '';
      load();
    }

    load();
  </script>
</body>
</html>

nginx.conf configures the web server nginx:

server {
    listen 80;

    location / {
        root /usr/share/nginx/html;
    }

    location /api/ {
        proxy_pass http://backend:8000/;
    }
}

Dockerfile describes how to build its image:

FROM nginx:1.29
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY index.html /usr/share/nginx/html/index.html

Build both images. Each build takes a few seconds. The first one also downloads its base image:

docker build -t messages-backend:1.0 backend/
docker build -t messages-frontend:1.0 frontend/

Import the images into your cluster. This takes about 15 seconds:

k3d image import messages-backend:1.0 messages-frontend:1.0 --cluster labs
...
INFO[0012] Successfully imported 2 image(s) into 1 cluster(s)

Explanation

The backend provides three endpoints:

EndpointDoes
GET /healthChecks the connection to the database and returns the Pod name
GET /messagesReturns all messages, the newest first
POST /messagesStores a new message

It reads the connection details of the database from environment variables and creates its table at the start. Its image installs the Python packages with uv, a fast replacement for pip that the Dockerfile copies from uv’s image.

The web page calls /api/messages; nginx serves the page and forwards everything under /api/ to http://backend:8000/ without the prefix, so /api/messages becomes /messages. backend is the name of the backend’s Service, which you create in Step 3.

k3d image import copies the images into the nodes of your cluster, so you don’t need a registry. The tag 1.0 matters: for an image with the tag latest, Kubernetes would try to download it from Docker Hub and fail.


Step 2: Deploy PostgreSQL

Create the file postgres.yaml in ~/labs/3.1 with a Secret, a Service and a StatefulSet for the database:

apiVersion: v1
kind: Secret
metadata:
  name: postgres
stringData:
  POSTGRES_USER: messages
  POSTGRES_PASSWORD: s3cr3t
  POSTGRES_DB: messages
---
apiVersion: v1
kind: Service
metadata:
  name: postgres
spec:
  selector:
    app: postgres
  ports:
    - port: 5432
      targetPort: 5432
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: postgres
spec:
  replicas: 1
  selector:
    matchLabels:
      app: postgres
  persistentVolumeClaimRetentionPolicy:
    whenDeleted: Delete
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
        - name: postgres
          image: postgres:18
          envFrom:
            - secretRef:
                name: postgres
          volumeMounts:
            - name: data
              mountPath: /var/lib/postgresql
          readinessProbe:
            exec:
              command: ["pg_isready", "-U", "messages"]
            periodSeconds: 5
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 1Gi

Create the resources:

kubectl apply -f postgres.yaml
secret/postgres created
service/postgres created
statefulset.apps/postgres created

The nodes download the PostgreSQL image first. Wait about 15 seconds and list the Pods and PVCs:

kubectl get pods
NAME         READY   STATUS    RESTARTS   AGE
postgres-0   1/1     Running   0          15s

If postgres-0 isn’t 1/1 yet, wait a moment and repeat the command.

kubectl get pvc
NAME              STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS   VOLUMEATTRIBUTESCLASS   AGE
data-postgres-0   Bound    pvc-bd41bde3-50d4-4bbe-97c1-894d8e18b107   1Gi        RWO            local-path     <unset>                 15s

Explanation

ResourceJob
SecretUser, password and name of the database, which the PostgreSQL image creates at its first start
ServiceGives the database the name postgres in the cluster
StatefulSetRuns PostgreSQL as postgres-0, with its own storage

volumeClaimTemplates lets the StatefulSet create a PVC for each of its Pods (data-postgres-0 for postgres-0). A database belongs in a StatefulSet: a Deployment could briefly run two PostgreSQL instances on the same data during an update. whenDeleted: Delete deletes the PVC together with the StatefulSet, so the Clean Up removes it as well. In production, you’d keep the default and protect the data.

The readiness probe runs pg_isready, which reports whether PostgreSQL accepts connections.


Step 3: Deploy the Backend

Create the file backend.yaml with a Deployment and a Service for the backend:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: backend
spec:
  replicas: 2
  selector:
    matchLabels:
      app: backend
  template:
    metadata:
      labels:
        app: backend
    spec:
      containers:
        - name: backend
          image: messages-backend:1.0
          env:
            - name: POSTGRES_HOST
              value: postgres
          envFrom:
            - secretRef:
                name: postgres
          readinessProbe:
            httpGet:
              path: /health
              port: 8000
            periodSeconds: 5
---
apiVersion: v1
kind: Service
metadata:
  name: backend
spec:
  selector:
    app: backend
  ports:
    - port: 8000
      targetPort: 8000

Create the resources:

kubectl apply -f backend.yaml
deployment.apps/backend created
service/backend created

Wait about 10 seconds and list the Pods:

kubectl get pods
NAME                       READY   STATUS    RESTARTS   AGE
backend-778d576b74-lcf45   1/1     Running   0          8s
backend-778d576b74-ztrhj   1/1     Running   0          8s
postgres-0                 1/1     Running   0          53s

If the backend Pods aren’t 1/1 yet, wait a moment and repeat the command. Call the backend from inside the cluster:

kubectl run client --image=busybox:1.37 --rm -it --restart=Never -- wget -q -O - http://backend:8000/messages
[]pod "client" deleted from default namespace

Explanation

The backend gets the same Secret as PostgreSQL with envFrom, plus the environment variable POSTGRES_HOST with the name of the database’s Service. [] is an empty list of messages: the backend reached the database and created its table. The response has no line break, so the message of kubectl follows right after [].

The readiness probe calls /health, which checks the connection to the database. A backend Pod only gets requests once it can reach the database.


Step 4: Deploy the Frontend

Create the file frontend.yaml with a Deployment and a NodePort Service for the frontend:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: frontend
spec:
  replicas: 1
  selector:
    matchLabels:
      app: frontend
  template:
    metadata:
      labels:
        app: frontend
    spec:
      containers:
        - name: frontend
          image: messages-frontend:1.0
---
apiVersion: v1
kind: Service
metadata:
  name: frontend
spec:
  type: NodePort
  selector:
    app: frontend
  ports:
    - port: 80
      targetPort: 80
      nodePort: 30088

Create the resources:

kubectl apply -f frontend.yaml
deployment.apps/frontend created
service/frontend created

Wait a few seconds and open http://localhost:30088 in your browser. If the page doesn’t load yet, wait a moment and reload it. Type a message and select Submit. It appears in the list below. Alternatively, store and read a message with curl:

curl -X POST -H "Content-Type: application/json" -d '{"text": "Hello Kubernetes"}' http://localhost:30088/api/messages
{"status":"ok"}
curl http://localhost:30088/api/messages
[{"id":1,"created_at":"2026-10-13T15:35:08.127450+00:00","text":"Hello Kubernetes"}]

Messages you submitted in the browser are listed as well, with their own id.

Explanation

A message takes this way through your cluster:

Browser -> NodePort 30088 -> frontend -> Service backend -> backend -> Service postgres -> postgres-0

Each part finds the next one by the name of its Service, as in 2.6. Only the frontend is reachable from your machine.


Step 5: Keep the Messages

Delete the database Pod and both backend Pods:

kubectl delete pod postgres-0
kubectl delete pod -l app=backend

Wait about 10 seconds, then reload the page in your browser or read the messages again:

curl http://localhost:30088/api/messages
[{"id":1,"created_at":"2026-10-13T15:35:08.127450+00:00","text":"Hello Kubernetes"}]

If you get 502 Bad Gateway, the new backend Pods aren’t ready yet. Wait a moment and repeat the command.

Explanation

The StatefulSet started a new postgres-0 with the same PVC, so the messages are still there. The Deployment replaced the backend Pods. They don’t store anything themselves, so any number of them can run.

Until a new backend Pod is ready, the frontend can’t forward any request and answers 502 Bad Gateway. The readiness probe keeps the new backend Pods out of the Service until they reach the database.


Optional Tasks

Finished early? Try these tasks. The following labs don’t depend on them. Each task lists the commands you need. Open the solution if you get stuck.

Task 1: Who Answered?

Call the health check of the backend through the frontend several times. Which Pods answer?

You know all the commands you need.

Solution

Call /api/health six times:

for i in 1 2 3 4 5 6; do curl -s http://localhost:30088/api/health; echo; done
{"status":"ok","pod":"backend-778d576b74-hlhs6"}
{"status":"ok","pod":"backend-778d576b74-8gxxh"}
{"status":"ok","pod":"backend-778d576b74-8gxxh"}
{"status":"ok","pod":"backend-778d576b74-hlhs6"}
{"status":"ok","pod":"backend-778d576b74-8gxxh"}
{"status":"ok","pod":"backend-778d576b74-hlhs6"}

The Service backend spreads the requests of nginx over both backend Pods.

Task 2: Look into the Database

Show the stored messages directly in PostgreSQL. The image contains the command-line client psql.

CommandEffect
kubectl exec <pod> -- psql -U <user> -c "<sql>"Runs an SQL statement with the PostgreSQL client in the Pod
Solution

Run psql in the database Pod:

kubectl exec postgres-0 -- psql -U messages -c "select * from messages"
 id |          created_at          |       text
----+------------------------------+------------------
  1 | 2026-10-13 15:35:08.12745+00 | Hello Kubernetes
(1 row)

With kubectl exec -it postgres-0 -- psql -U messages, you get an interactive SQL prompt. Leave it with \q.

Task 3: Version 1.1

Change the heading of the web page to Message Board 1.1 and roll out the new version of the frontend.

You know all the commands you need.

Solution

Change the heading in index.html in ~/labs/3.1/frontend:

  <h1>Message Board 1.1</h1>

Build the image with a new tag and import it:

docker build -t messages-frontend:1.1 ~/labs/3.1/frontend/
k3d image import messages-frontend:1.1 --cluster labs

Change the image in frontend.yaml to messages-frontend:1.1 and apply it:

kubectl apply -f ~/labs/3.1/frontend.yaml

Reload the page. It shows the new heading. A new tag for every version is important: with the same tag, Kubernetes would see no change in the manifest and keep the old Pods.


Clean Up

Delete all resources of this lab:

kubectl delete -f ~/labs/3.1/
deployment.apps "backend" deleted from default namespace
service "backend" deleted from default namespace
deployment.apps "frontend" deleted from default namespace
service "frontend" deleted from default namespace
secret "postgres" deleted from default namespace
service "postgres" deleted from default namespace
statefulset.apps "postgres" deleted from default namespace

The PVC of the database and the stored messages are deleted as well. The images stay in your cluster. The next chapter uses them again.