Testing Kubernetes Load Balancer via Replicas (Kubernetes)

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 socket
from flask import Flask
HOSTNAME = 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-slim
WORKDIR /app
COPY . .
RUN pip install --no-cache-dir --upgrade pip && pip install -r requirements.txt && pip install gunicorn
ENV FLASK_APP=main.py
RUN chmod +x ./docker-entry.sh
EXPOSE 5000
ENTRYPOINT [ "./docker-entry.sh" ]

and an entry point script that utilises Gunicorn to run the Flask within container:

#!/bin/bash
gunicorn -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/v1
kind: Deployment
metadata:
name: dep-flask-hello
spec:
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: v1
kind: Service
metadata:
name: lb-hello
spec:
type: LoadBalancer
ports:
- port: 80
targetPort: 5000
selector:
name: geektechstuff-flask

Kubectl can then be used to display the running pods:

kubectl get pods

Testing Kubernetes Load Balancer via Replicas (Kubernetes)
Output of 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:

Traffic going to 85cb7468fc-nnc9pq
And a reload later, traffic going to a different container

Related Posts