DEV Community

Cover image for How to Build and Deploy a Flask Application to Kubernetes Cluster
Bravin Wasike
Bravin Wasike

Posted on • Updated on • Originally published at sweetcode.io

How to Build and Deploy a Flask Application to Kubernetes Cluster

This tutorial will teach you how to build and deploy a Flask application to a Kubernetes Cluster.

Kubernetes is a computer orchestration tool that assists in the deployment of container applications. Kubernetes is a powerful tool that automates the management, deployment, and scaling of containerized applications in a Kubernetes cluster.

A Kubernetes cluster contains a set of worker nodes that run the deployed containerized applications. The worker nodes have pods that create multiple instances of the same application. The Kubernetes cluster automatically manages the resources required to run the applications and perform auto-scaling. A Kubernetes cluster can run on cloud-based providers such as Amazon Elastic Kubernetes Service, Azure Kubernetes Service and Google Kubernetes Engine. It can also run locally on a Minikube Kubernetes Cluster.

Before deploying any application to a Kubernetes cluster, you first containerize the application using Docker. Docker bundles all the dependencies and source code the application requires to run.

In this tutorial, you will start by creating a simple "Hello world" Flask application and then run it locally. You will then use Docker to containerize the Flask application and also run the Docker container. Finally, you will deploy the dockerized Flask to the Minikube Kubernetes Cluster. Let's get started with our project!

Prerequisites

This tutorial assumes you have some basic Docker knowledge and have the following set up on your machine:

Creating the Flask application

Flask is an open-source Python micro framework for building web applications. You will use the Flask framework to create a simple "Hello world" application. To install Flask, let's run the following command in your terminal:

pip install flask
Enter fullscreen mode Exit fullscreen mode

The command above will install the Flask framework and all the dependencies required to run the application. After successfully installing the framework, create a working directory named flask-application and open it in VS Code. In the working directory, create a file named app.py and paste in the following code:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "<p>This is a Hello World application</p>"

if __name__ == '__main__':
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

The code above has a hello_world function which will return This is a Hello World application. To run this simple Flask application, execute the following command in your terminal:

python app.py
Enter fullscreen mode Exit fullscreen mode

The command will run the Flask application in the web browser, as shown in the image below:

Image description

You have successfully run the application locally. Lets's now use Docker to containerize the application.

Containerising the Flask application with Docker

You create a Dockerfile which the Docker Engine will use to containerize the Flask application. The Dockerfile has several commands that build the Docker image for the application. The Docker image will have all the source code, tools, and dependencies the application requires to run.

You also need to create a requirements file that will specify all the dependencies and tools required to run the Flask application. To start, in the working directory, create a new file and name it requirements.txt and add the following:

flask
Enter fullscreen mode Exit fullscreen mode

The Flask application only requires the flask framework to run. Next, in the working directory, create a new file named Dockerfile and paste in the following code:

# You will use python:3.10-alpine as the base image for building the Flask container
FROM python:3.10-alpine

# It specifies the working directory where the Docker container will run
WORKDIR /app

# Copying all the application files to the working directory
COPY . .

# Install all the dependencies required to run the Flask application
RUN pip install -r requirements.txt

# Expose the Docker container for the application to run on port 5000
EXPOSE 5000

# The command required to run the Dockerised application
CMD ["python", "/app/app.py"]
Enter fullscreen mode Exit fullscreen mode

To build a Docker image using the above Dockerfile, run the following command in your terminal:

docker build -t bravinwasike/flask-kubernetes .
Enter fullscreen mode Exit fullscreen mode

The command will build a Docker image named bravinwasike/flask-kubernetes and produce the following output:

Image description

Pushing the Docker image to Docker Hub

After creating the Docker image, ensure you push the Docker image into your Docker Hub repository using the following commands:

  1. Log in to the Docker hub from your terminal
docker login
Enter fullscreen mode Exit fullscreen mode
  1. Pushing the Docker image to Docker Hub
docker push bravinwasike/flask-kubernetes
Enter fullscreen mode Exit fullscreen mode

Running a Docker Container

To run a Docker container using the created Docker image, use the following command:

docker run -p 5000:5000 bravinwasike/flask-kubernetes:latest
Enter fullscreen mode Exit fullscreen mode

The command will run the Docker container and expose our application on port 5000. We can also view our containerized application on a web browser shown below:

Image description

The next step is to deploy the containerized Flask application to the Minikube Kubernetes Cluster.

Getting started with the Minikube Kubernetes Cluster

Minikube is a tool that runs a single-node Kubernetes cluster on your local machine. To run Minikube, all you need is Docker Desktop set up on your computer. Docker Desktop comes with Minikube already configured. Minikube runs on Windows, Linux, and macOS. Minikube is best suited for running simple applications and testing purposes.

To check the installed Minikube version, run the following command:

minikube version
Enter fullscreen mode Exit fullscreen mode

To run Minikube using the Docker driver, use the following command:

minikube start --driver=docker
Enter fullscreen mode Exit fullscreen mode

The code above produces the following output:

Image description

The output shows the Minikube Kubernetes Cluster has started running. The next step is to deploy the containerized Flask application to the created Minikube Kubernetes Cluster.

Deploying to the Minikube Kubernetes Cluster

You will deploy the containerized Flask application to the created Minikube Kubernetes Cluster using the Kubernetes CLI. Kubernetes CLI known as kubectl is a command line interface tool that allows you to deploy applications to a Kubernetes Cluster. It also allows you to manage and interact with all the resources for the Kubernetes cluster.

To install the Kubernetes CLI, use the following choco command:

choco install kubernetes-cli
Enter fullscreen mode Exit fullscreen mode

To check the version of the installed Kubernetes CLI, execute the following command in your terminal:

kubectl version --client
Enter fullscreen mode Exit fullscreen mode

The next step is to create a deployment.yaml file which kubectl will use to deploy the application to the Minikube Kubernetes cluster.

Creating the deployment.yaml file

The deployment file will specify the number of instances/replicas of the containerized application. It will also show the resources required to run the application pods. In the working directory, create a new file named deployment.yaml and paste the following code snippet:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: flask-app-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: test-app
  template:
    metadata:
      labels:
        app: test-app
    spec:
      containers:
      - name: test-app
        image: bravinwasike/flask-kubernetes:latest
        resources:
          limits:
            memory: "128Mi"
            cpu: "500m"
        ports:
        - containerPort: 5000
---

apiVersion: v1
kind: Service
metadata:
  name: flask-app-service
spec:
  selector:
    app: flask-app-deployment
  ports:
  - port: 6000
    targetPort: 5000
  type: LoadBalancer
Enter fullscreen mode Exit fullscreen mode

The code snippet above has two parts: Deployment and Service

  1. Deployment This part describes the intended number of multiple instances/replicas or pods for the deployed application. In our case, we will have 3 pods. If one pod fails the other ones will take over. It ensures zero downtime and the application's reliability.

You will also use the bravinwasike/flask-kubernetes docker image we had earlier pushed to Docker Hub to create our application's container. In this part, we specify the resources (CPU and memory) that each pod will need to run. It also shows the port (5000) our container is running. Our Deployment is named flask-app-deployment.

  1. Service It acts as a load balancer that distributes the application traffic. It will distribute the number of API calls to the app instances/pods equally. The service also exposes our deployed application outside the Minikube Kubernetes Cluster using an external IP address. It makes it possible to access the application on the web browser. Our service is named flask-app-service

To deploy the application to the Minikube Kubernetes cluster, execute the following kubectl command in your terminal:

kubectl apply -f deployment.yaml
Enter fullscreen mode Exit fullscreen mode

The command above will use the deployment.yaml to automatically create containers and deploy them to the Minikube Kubernetes cluster. It will create 3 application instances/pods, and each pod will use the specified resources. To see the deployment, use the following code:

kubectl get deployment
Enter fullscreen mode Exit fullscreen mode

Image description

The output shows our flask-app-deployment.

To see the service, use the following code:

kubectl get service
Enter fullscreen mode Exit fullscreen mode

Image description

The output shows our flask-app-service is running.

Getting the pods

To see the pods, use the following code:

kubectl get pods
Enter fullscreen mode Exit fullscreen mode

Image description

The output shows the three running pods.

The Minikube deployment dashboard

To view the Minikube deployment dashboard, use the following command:

minikube dashboard
Enter fullscreen mode Exit fullscreen mode

The code displays the following in your web browser:

Image description

Image description

The output shows the running Deployments, Services, and Pods in the Minikube Kubernetes Cluster.

Accessing the containerized application

You will expose the flask-app-service to access the application outside the Minikube Kubernetes Cluster. You will use an external IP address and access the application on the web browser. To expose the service, use the following minikube command:

minikube service flask-app-service
Enter fullscreen mode Exit fullscreen mode

You can now access our containerized Flask application using the following external IP address: http://127.0.0.1:13678 Minikube Kubernetes Cluster generates.

Image description

Click on the URL to access the application on the web browser. The application output:

Image description

You have successfully deployed the Flask application to the Minikube Kubernetes Cluster and accessed the application as a Kubernetes Cluster service.

Conclusion

In this tutorial, you have learned how to deploy a Flask application to a Kubernetes Cluster. You started by creating a simple "Hello world" Flask application and ran it locally. You then used Docker to containerize the Flask application and also ran the Docker container.

You created a Minikube Kubernetes Cluster and ran Kubernetes locally on our machine. Finally, you deployed the dockerized Flask to the Minikube Kubernetes Cluster. The complete code for this tutorial is found here in Git Hub.

If you like this tutorial let's connect on Twitter. Thanks for Reading and Happy Learning!

Top comments (0)