DEV Community

Yogendra Tamang
Yogendra Tamang

Posted on

Deploy Flask App on Kubernetes - 1

Introduction

This is part one of two part series:
Here, I will discuss about creating simple flask app, containerizing it and pushing it to image repository DockerHub.

Prerequisites

Create Flask APP

Lets create requirements.txt files for our app.

Flask==1.1.2
gunicorn==20.0.4

Flask comes with one development server, but we will use production-ready server, like gunicorn.

Create src folder and app.py file inside that. Our App will have only two endpoints:

  • / -- returns welcome message.
  • /names -- lists countries I visited :P
from flask import Flask, jsonify
app = Flask(__name__)
from flask import Flask, jsonify
app = Flask(__name__)

country_list = [
    'Nepal',
    'India',
    'Germany',
    'Netherlands'
]

@app.route('/')
def index():
    response_dict = {
        "message": "Welcome to FlaskApp"
    }
    return jsonify(response_dict)

@app.route('/names')
def countries():
    country_dict = {
        'countries': country_list,
        'total': len(country_list)
    }
    return jsonify(country_dict)


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=8083)

Run your app in debug mode

python src/app.py

Run your app from gunicorn

gunicorn --chdir src app:app -w 2 -bind 0.0.0.0:8083

Lets create deploy.sh, we will execute this directly

#! /bin/sh
gunicorn --chdir src app:app -w 2 -b 0.0.0.0:8083

(Make it executable: chmod +x deploy.sh)

You can browse http://localhost:8083/
Output

Building Docker Image

Lets write Dockerfile to create docker image of our app.
Here I am going with python-3.7-slim-buster.

This is one of light weight and recommended images to use.
Follow this if you want to learn more about other python images.

FROM python:3.7-slim-buster

COPY requirements.txt .

RUN pip install -r requirements.txt

COPY . /app

WORKDIR /app

ENTRYPOINT [ "./deploy.sh" ]

Now run following command to build image

docker build -t simple-flask-app .
This will take some time depending on your network speed. Once completed you will see success message like this

Run your docker image

docker run -p 8888:8083 simple-flask-app
If you browse http://localhost:8888/names, you will see following output.

Curl Output

Now Push your image to DockerHub using following commands

$ docker tag simple-flask-app <dokcer-hub-account>/simple-flask-app

$ docker push <dokcer-hub-account>/simple-flask-app

If you are not logged in, log in first.

$ docker login

Top comments (0)