Dockerize Simple Python Flask App

Introduction :

In this blog, we will concentrate on writing Dockerfile to dockerize the simple hello world python flask app.

Prerequisite:

  • Docker
  • Linux Machine
  • Python 2.7 or above.

Step 1 | Creating Dockerfile for your app.

Application Folder Structure

Web
____ app.py
____ requirements.txt
____ Dockerfile

app.py

from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0')

requirements.txt

Flask==0.12

Dockerfile:

Dockerfile consists set of instructions which are used to create docker image of the application. A Dockerfile contains all those commands that require starting the app.
We will build image with the latest version of ubuntu,

# Format: FROM    repository[:version]
FROM ubuntu:latest

Copy the app in our remote container,

COPY . /app
WORKDIR /app

We will begin with the installing necessary dependencies to run the app,

RUN apt-get update -y
RUN apt-get install -y python-pip python-dev build-essential
RUN pip install -r requirements.txt

We will set the Entrypoint which will tell docker to run python inside the docker container.

ENTRYPOINT ["python"]

To run the app we will add command ,

CMD ["app.py"]

So finally we will get Dockerfile as ,

# Format: FROM    repository[:version]
FROM ubuntu:latest
RUN apt-get update -y
RUN apt-get install -y python-pip python-dev build-essential
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
ENTRYPOINT ["python"]
CMD ["app.py"]

Step 2 | Build the docker image

Run the following command to create the docker image from web directory,

$ docker build -t helloworldapp:latest .

Step 3 | Run the docker container

Run the docker container from a created image,

$ docker run -d -p 5000:5000 helloworldapp

You can access the app using hostname:5000 port. If you are running this on locally then you can access it by localhost:5000
You can check the running containers with docker ps command,

docker ps 
CONTAINER ID IMAGE COMMAND
fb5ce111110d helloworldapp "python app.py" ...
Show your support

Clapping shows how much you appreciated Jakir Patel’s story.