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:
importosimportsocketfromcontextlibimportasynccontextmanagerimportpsycopgfromfastapiimportFastAPIfrompydanticimportBaseModeldefconnect():returnpsycopg.connect(host=os.environ["POSTGRES_HOST"],dbname=os.environ["POSTGRES_DB"],user=os.environ["POSTGRES_USER"],password=os.environ["POSTGRES_PASSWORD"])@asynccontextmanagerasyncdeflifespan(app):withconnect()asconn:conn.execute("""
create table if not exists messages (
id serial primary key,
created_at timestamptz not null default now(),
text text not null
)
""")yieldapp=FastAPI(lifespan=lifespan)classMessageInput(BaseModel):text:str@app.get("/health")defhealth():withconnect()asconn:conn.execute("select 1")return{"status":"ok","pod":socket.gethostname()}@app.get("/messages")deflist_messages():withconnect()asconn: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}forid,created_at,textinrows]@app.post("/messages")defcreate_message(message:MessageInput):withconnect()asconn:conn.execute("insert into messages (text) values (%s)",(message.text,))return{"status":"ok"}
requirements.txt lists the Python packages it needs:
...
INFO[0012] Successfully imported 2 image(s) into 1 cluster(s)
Explanation
The backend provides three endpoints:
Endpoint
Does
GET /health
Checks the connection to the database and returns the Pod name
GET /messages
Returns all messages, the newest first
POST /messages
Stores 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:
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
Resource
Job
Secret
User, password and name of the database, which the PostgreSQL image creates at its first start
Service
Gives the database the name postgres in the cluster
StatefulSet
Runs 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:
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:
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:
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 12345 6;do curl -s http://localhost:30088/api/health; echo;done
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.