Deploying flask app to Kubernetes using Minikube
Tags: kubernetes, deployment, devops
Published: 2024-01-31 17:04:20

#### Introduction
[Kubernetes](https://kubernetes.io/) manages the deployment, scaling, and operation of containerized applications across a cluster of machines. Kubernetes relies on tools such as container runtimes like Docker, to run the containers.

Before deploying the application with Kubernetes, you need to containerize the application using docker. This article shows how to deploy a Flask application on Ubuntu 22.04 using Minikube; a Kubernetes tool for local deployment for testing and free offering. Alternatively, you can deploy your container apps using Cloud providers such as [GCP](https://cloud.google.com/gcp?utm_source=google&utm_medium=cpc&utm_campaign=emea-emea-all-en-bkws-all-all-trial-e-gcp-1707574&utm_content=text-ad-none-any-DEV_c-CRE_500236788675-ADGP_Hybrid+%7C+BKWS+-+EXA+%7C+Txt+~+GCP+~+General%23v3-KWID_43700060393213451-aud-606988878614:kwd-87853815-userloc_1009824&utm_term=KW_gcp-NET_g-PLAC_&&gad_source=1&gclid=EAIaIQobChMIgufY2OGHhAMVP6aDBx2xBwwaEAAYASAAEgKx_vD_BwE&gclsrc=aw.ds)(Google Cloud), [Azure](https://azure.microsoft.com/en-us)(Microsoft) or [AWS](https://aws.amazon.com/free/?gclid=EAIaIQobChMI9NPy_-GHhAMVM5GDBx1Acw8kEAAYASAAEgKRhfD_BwE&trk=2d3e6bee-b4a1-42e0-8600-6f2bb4fcb10c&sc_channel=ps&ef_id=EAIaIQobChMI9NPy_-GHhAMVM5GDBx1Acw8kEAAYASAAEgKRhfD_BwE:G:s&s_kwcid=AL!4422!3!645125273261!e!!g!!aws!19574556887!145779846712)(Amazon).


####Prerequisites

1.[Docker installed on your device.](https://docs.docker.com/engine/install/ubuntu/#install-using-the-repository).**NOTE: Make sure your docker version is below 25; to prevent errors associated with compatibility. We will be using Docker version 24.0.7.)**

2.[Minikube installed on your Device](https://www.linuxbuzz.com/install-minikube-on-ubuntu/).
3.[A Github repository to save your project files](https://github.com/).
4.[Flask installed in your device](https://tecadmin.net/how-to-install-flask-on-ubuntu/).
5.A Dockerfile.
6.Docker-compose yaml file.
7.Deployment and Service yaml files.
8.A requirement.txt file for flask dependencies.


#### Step 1:Creating a  Dockerfile with the following:

In the file structure of the Dockerfile, we copy the requirements.txt before the files because of easier caching when modifications are done,and you can have an easier build with Docker.

(Ensure you add Flask and werkzeug with their consecutive versions in the requirements.txt file.)

```
# Use an official Python runtime as a parent image
FROM python:3.10.12

# Install python3-venv
RUN apt-get update && \
    apt-get install -y python3-venv
# Set the working directory to the name of the application
WORKDIR /app

# Copy the requirements file into the container at the application 
COPY requirements.txt /app/

# Create a virtual environment in /opt/env
RUN python3 -m venv /opt/env

# Install any needed packages specified in requirements.txt
RUN /opt/env/bin/pip install --no-cache-dir -r requirements.txt

# Copy the current directory contents into the container at the application
COPY . /app/

# Set environment variables
ENV PATH="/app/venv/bin:$PATH"

# Make port 5000 available to the world outside this container
EXPOSE 5000

# Run flask application when the container launches
CMD ["/opt/env/bin/python", "-m","flask", "run","--host=0.0.0.0"]

```

####Step 2:Creating a docker-compose yaml file with the following:

```
version: '3'

services:
  web:
    build: .
    ports:
      - "5000:5000"
    environment:
      - DATABASE_URL=sqlite:////data/mydatabase.db  # Set the desired database file path
    volumes:
      - ./:/data # Set the desired file path

  sqlite3:
    image: nouchka/sqlite3:latest
    stdin_open: true
    tty: true
    volumes:
      - ./:/data # Set the desired file path

```

#### Step 3: Run Docker Compose Commands.

`docker-compose build`
`docker-compose up`

#### Step 4: Load the Docker Image to Minikube.
Minikube is best suited for local development and testing, but it doesn't provide the same features and scalability as a full-scale production Kubernetes cluster.
Once installed, make sure to load the image name that you created with docker using this command 
`minikube image load your-image-name:tag`.We used this for the app:`minikube image load flask_web:latest`. Run` minikube image list `to check if the image exists.


#### Step 5: Create a Kubernetes Deployments file.
**Note: Make sure to add the image pull policy line as `IfNotPresent `to mitigate pull errors from images you have.**

```
apiVersion: apps/v1
kind: Deployment
metadata:
  name: your-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      app: your-app
  template:
    metadata:
      labels:
        app: your-app
    spec:
      containers:
      - name: your-container
        image: your-image-name:tag
        ports:
        - containerPort: 80
        imagePullPolicy: IfNotPresent

```

#### Step 6: Apply the deployment file to Minikube.
`kubectl apply -f deployment.yaml
`
#### Step 7: Create a service file that exposes the flask application. 

```
apiVersion: v1
kind: Service
metadata:
  name: your-service
spec:
  selector:
    app: your-app
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80
  type: LoadBalancer

```
####Step 8: Apply the service in minikube.
`kubectl apply -f service.yaml`

####Step 9: Access the service.
To access the service, run the following command: 
`minikube service your-service` If successful, it will launch in your browser. 

####Step 10: Stopping and deleting the Minikube cluster.
Once done, make sure you stop and delete the minikube cluster using the following commands:
`minikube stop
minikube delete`

####Conclusion

In conclusion, we were able to deploy a container application in Kubernetes using Minikube as a testing tool which offered the best local testing environment. Kubernetes is the best tool for container orchestration, deployment, and scaling at the high end, while Docker complements Kubernetes by containerizing its applications.