In this post, I'm going to create a simple Flask app and will run it inside a docker container.
docker - We need to install docker for this. To install docker on your system follow this link.
A Flask app - You can find the sample code here.
The Docker Hub image
Since Docker Hub doesn’t have an official Flask repository (at the time of this writing), I’ll be building my own image. There are some non-official images available but it's generally recommended to make your own Dockerfile.
Let's Create Our Dockerfile
Make Project directory
Start with creating a new directory; let’s call it flask_project:
Our flask_app.py file will look something like this:
# simple Flask app From flask import Flask app = Flask(__name__) @app.route("/hello") def hello(): return "hello user!!" @app.route("/") def index(): return "hello. You have arrived at '/'" if __name == '__main__': app.run(debug=True, host='0.0.0.0', port=5005)
Now, we need to include Flask in our
Inside our project directory, we'll create a file named - Dockerfile. your directory will look something like this -
\-Project | |-flask_app.py |-Dockerfile |-Requirements.txt
Open up the
Dockerfile and add following -
FROM ubuntu:16.04 MAINTAINER Damanpreet Singh "email@example.com" RUN apt-get update -y RUN apt-get install -y python-pip python-dev build-essential # We copy just the requirements.txt first to leverage Docker cache COPY . /app WORKDIR /app RUN pip install -r requirements.txt ENTRYPOINT [ "python" ] CMD [ "flask_app.py" ]
FROM ubuntu:16.04 - We are using ubuntu 16.04 as base image
MAINTAINER - Used for author field of image( used when pushing image to docker hub).
RUN - It tells docker to run the commands specified. In our case, the commands are apt-get update and install
COPY - copies file from first parameter( . ) from host to the destination parameter(/app).
ENTRYPOINT - configures the container to run as an executable; only the last ENTRYPOINT instruction executes.
Building Docker Image
To build docker image from our Dockerfile, run following command -
$docker build -t flask-web-app .
-t - lets you add custom tag name to the image- for me it is flask-web-app.
. - here we need to specify the location of Dockerfile. Since, I'm in the same directory, I'm using
Running Docker Image
To run the Docker Image, run following command -
$ docker run -p 5000:5005 flask-web-app
-p is used to specify port forwarding. Here we are specifying docker to forward port no. 5005 of image to port no. 5000 of host OS.
flask-web-app is the name of the image that we want to run.
We can find the container runtime details using following command -
See the Results
To see the results, open the web browser and point it to http://localhost:5000/
Top comments (2)
As a base image you can use Python images from docker hub e.g. python:3.7-buster (for Debian flavor if you want to use apt), saves you from installing manually Python in your image.