How to Build and Deploy a Flask Application to Kubernetes Cluster
Tags: devops, docker, kubernetes, flask
Published: 2023-05-17 14:22:49

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](https://aws.amazon.com/eks/), [Azure Kubernetes Service](https://azure.microsoft.com/en-us/products/kubernetes-service/) and [Google Kubernetes Engine](https://cloud.google.com/kubernetes-engine). It can also run locally on a [Minikube](https://minikube.sigs.k8s.io/docs/start/) 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](https://docs.docker.com/get-docker/) knowledge and have the following set up on your machine:

- [VS Code](https://code.visualstudio.com/Download) text editor.
- [Docker Desktop](https://www.docker.com/products/docker-desktop) installed onto 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:

```python
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:

```python
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)
```
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
python app.py
```
The command will run the Flask application in the web browser, as shown in the image below:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wckpeyssi9yly9jsjulz.png)

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:

```python
flask
```
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:

```docker
# 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"]
```
To build a Docker image using the above `Dockerfile`, run the following command in your terminal:

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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kg5uuvhbwmybzq3q27pn.png)

### 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
docker login
```
2. Pushing the Docker image to Docker Hub

```docker
docker push bravinwasike/flask-kubernetes
```
### Running a Docker Container
To run a Docker container using the created Docker image, use the following command:

```docker
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:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v7ar5kmrdh5evo08f30l.png)

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
minikube version
```
To run Minikube using the Docker driver, use the following command:

```minikube
minikube start --driver=docker
```
The code above produces the following output:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vkel4mdarqov3q57mv63.png)

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](https://kubernetes.io/docs/tasks/tools/). 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
choco install kubernetes-cli
```
To check the version of the installed Kubernetes CLI, execute the following command in your terminal:

```kubectl
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:

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

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

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
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
kubectl get deployment
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eis75ibje1ymlszof8fc.png)

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

To see the service, use the following code:

```kubectl
kubectl get service
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/36k5ihjud3g73rssjq9h.png)

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

### Getting the pods
To see the pods, use the following code:

```kubectl
kubectl get pods
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t0hs1c67qa2m4p96x540.png)

The output shows the three running pods. 

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

```minikube
minikube dashboard
```
The code displays the following in your web browser:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g1a72nzzexdt4q0f5t3z.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vqptmw369nw2bra120i6.png)

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
minikube service flask-app-service
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/or54k9u1ur9dk7lo9zpt.png)

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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dp0lnlqflbwtbmkvme1i.png)

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](https://github.com/Bravinsimiyu/flask-kubernetes) in Git Hub.

If you like this tutorial let's connect on [Twitter](https://twitter.com/wasike_bravin). Thanks for Reading and Happy Learning!