Lets find out how to build a simple flask webserver app in docker

Go ahead a create a file - app.py and copy the below contents.

from flask import Flask

app = Flask(__name__)

@app.route('/health')
def health_check():
    return 'success'


@app.route('/')
def hello_world():
    return 'hello world'

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

Most of the things in above code are explanatory. Yay, python!!

Couple of things for people who are not familiar with flask.

@app.route('/health')
def health_check():
    return 'success'
  • Whenever we get a request for ‘/health’, method health_check() will be executed, in this case, we will get a response with ‘success’ string.

if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0', port=4000)
  • Python have couple of special variables, so when you run your program as python app.py as a standalone program, compiler will initialise __name__ variable as __main__. During the run time if block will get triggered and app.run will be executed. The advantage of this usage will be when someone else exports your program as a module, during the compile time of the program __name__ won’t be initialised since its not a standalone program, so people can invoke your program whenever they want.

Now create a file Dockerfile with the following contents.

FROM ubuntu:latest
RUN apt-get update && apt-get install -y --no-install-recommends \
    python-pip \
    python-dev \
    build-essential \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
ENTRYPOINT ["/bin/bash", "/app/start.sh"]

We have declared two files requirements.txt and start.sh which we haven’t defined yet.

Create requirements.txt with the following contents.

Flask

Create start.sh with the following contents

#!/bin/bash
python app.py

We can start building image by executing docker build -t flaskapp . in working directory.

Once the image is built, you will be able to see it by executing docker images

To run the image, execute docker run -p 1234:4000 -d flaskapp. You will be able to see the running docker by executing docker ps.

You will be able to see the server running on your localhost:1234.