How To Deploy Flask Application Using Docker On Kubernetes

Shanikumar
2 min readFeb 8, 2024

--

Prerequisites:

Step1. Create simple flask app

Flask is a python lightweight framwork for web application with minimal no of code you can develope your application in no time.

Create requirements.txt file that contains all library and package for your application and app.py file for your application.

flask==3.0.2
from flask import Flask, jsonify

app = Flask(__name__)

@app.route("/", methods=["GET"])
def home():
data = {
"name": "Shani Kumar",
"age": 26,
"address": "Noida sector 15"
}

return jsonify(data), 200


if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)

Step2. Dockerize your application create a docker file for your application.

file name should be without any extention -> Dockerfile

FROM python:3.10-alpine3.18
RUN mkdir -p /opt/app
WORKDIR /opt/app
COPY . /opt/app
RUN pip install -r requirements.txt
EXPOSE 5000
CMD ["python3", "app.py"]

Step3. Create docker image for your application

docker build -t flaskapiimage .

Step 4. Create a container from this image that will run your app.

docker run --name flaskapicontainer -p 5000:5000 -it flaskapiimage

Step5. Push your image on docker hub .

Create docker hub account and login via your account credentials

docker login
docker tag flaskapiimage your_docker_hub_username/your_repo:v1
docker push your_username/your_repo:v1

Step 6. Now we will deploy our app on kubernetes via minikube.

Start minikube

minikube start

Create a deployment for your app

kubectl create deploy flaskapideploy --image=your_docker_hub_username/your_repo:v1 
kubectl get deploy
kubectl get pods

deployement will automatic create pods. this will take care of your pods it manage auto scaling and auto healing thats why your application will not go down.

Step 7. Create service for your deployment so that the app can be accessed by outside of minikube cluster.

kubectl expose deployment flaskapideploy --name=flaskapisvc --type=NodePort --port=80 --target-port=5000
kubectl get svc

To check Pods, Deployment etc on web app

minikube dashboard --url

http://127.0.0.1:41787/api/v1/namespaces/kubernetes-dashboard/services/http:kubernetes-dashboard:/proxy/

To Access the application outside of cluster

minikube service flaskapisvc --url

Now access the url on browser.

If you want to access via your specific port no then you need to port forwarding.

kubectl port-forward svc/flaskapisvc 3000:80

Now open browser type 127.0.0.1:3000 you can access your app.

Next we will add ingress for this so that we can access our app without specify port no.

Check -> how to add ingress

--

--