How to Deploy a Flask Application to a Kubernetes Cluster

248 VIEWS

· · · ·

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!

Prerequistites

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. We 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

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(host='0.0.0.0', debug=True)

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

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

We have successfully run the application locally. Lets’s now use Docker to containerize the application.

Containerising the Flask Application with Docker

We 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. 

We 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

Our 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:

# We 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 Dockerized application
CMD ["python", "/app/app.py"]

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

docker build -t bravinwasike/flask-kubernetes .

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

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
  2. Pushing the Docker image to Docker Hub
    docker push bravinwasike/flask-kubernetes

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

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:

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 for testing purposes.

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

minikube version

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

minikube start --driver=docker

The code above produces the following output:

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

We 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

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

kubectl version --client

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

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. 

We 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`.

2. 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

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

The output shows our `flask-app-deployment`.

To see the service, use the following code:

kubectl get service

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

Getting the Pods

To see the pods, use the following code:

kubectl get pods

The output shows the three running pods. 

The Minikube Deployment Dashboard

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

minikube dashboard

The code displays the following in your web browser:

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

Accessing the Containerized Application

We will expose the `flask-app-service` to access the application outside the Minikube Kubernetes Cluster. We 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

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

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

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

Conclusion

In this tutorial, we have learned how to deploy a Flask application to a Kubernetes Cluster. We started by creating a simple “Hello world” Flask application and ran it locally. Then we used Docker to containerize the Flask application and also ran the Docker container.

We created a Minikube Kubernetes Cluster and ran Kubernetes locally on our machine. Finally, we deployed the dockerized Flask to the Minikube Kubernetes Cluster. The complete code for this tutorial is found here in Git Hub. Thanks for reading, and Happy Learning!


Bravin Wasike holds an undergraduate degree in Software Engineering. He is currently a freelance data scientist and machine learning engineer. He is passionate about machine learning and deploying models to production using Docker and Kubernetes. Bravin also loves writing articles on machine learning and various advances in the technological industry. He spends most of his time doing research and learning new skills in order to solve different problems.


Discussion

Click on a tab to select how you'd like to leave your comment

Leave a Comment

Your email address will not be published.

Menu
Skip to toolbar