I previously blogged about deploying a replica set of nginx in Kubernetes, with the same static web pages shared from storage. I then did a post about using a load balancer such as Metallb in Kubernetes, with pods available externally via the load balancer. But how about mixing the two together….
Some Python (Flask)
When a pod launches in Kubernetes it gets a unique name, just as containers in Docker get unique names. A little bit of Python (thanks Socket!) can be used to get the name, and then some Flask magic can return it as web page:
import socketfrom flask import FlaskHOSTNAME = socket.gethostname()app = Flask(__name__)@app.route("/")def hello_word(): hello = "<p> Hello from: "+HOSTNAME+"</p>" return hello
A Docker file later…
The Python returns a Hostname but how to get this into the Kubernetes cluster. A Dockerfile helps to containerise the Python:
FROM python:3.15.0a6-slimWORKDIR /appCOPY . .RUN pip install --no-cache-dir --upgrade pip && pip install -r requirements.txt && pip install gunicornENV FLASK_APP=main.pyRUN chmod +x ./docker-entry.shEXPOSE 5000ENTRYPOINT [ "./docker-entry.sh" ]
and an entry point script that utilises Gunicorn to run the Flask within container:
#!/bin/bashgunicorn -b 0.0.0.0:5000 main:app
I’ve hosted the image on Docker Hub at: https://hub.docker.com/repository/docker/geektechstuff/flask-hello-world/
Deploying a replica set into Kubernetes
Using a similar deployment file as per my K3S Cluster (Kubernetes) post, I can launch 5 replicas of my “flask-hello-world” container.
apiVersion: apps/v1kind: Deploymentmetadata: name: dep-flask-hellospec: replicas: 5 selector: matchLabels: name: geektechstuff-flask template: metadata: labels: name: geektechstuff-flask spec: containers: - name: flask-hello-world image: geektechstuff/flask-hello-world:latest ports: - containerPort: 5000
And a service that creates a load balancer and targets any traffic hitting port 80 onto port 5000 of the containers. The load balancer selects the containers based on the labels:
apiVersion: v1kind: Servicemetadata: name: lb-hellospec: type: LoadBalancer ports: - port: 80 targetPort: 5000 selector: name: geektechstuff-flask
Kubectl can then be used to display the running pods:
kubectl get pods

Visiting the IP address of the load balancer sends the traffic onto a container, and a refresh / reload of the page shows that the load balancer is balancing traffic to different containers as the hostname displayed changes:





Leave a comment