Geek Culture
Published in

Geek Culture

How to dockerize your Flask application

Dockerize a minimalistic flask application

Introduction:

The objective of this post is to dockerise a minimalistic flask application. Let’s take an example of a simple flask program and dockerise it.

A Simple Flask Application:

The below code is a bare minimum flask application with a single end point /hello. Let’s say the module name is my_flask.py.

my_flask.py

from flask import Flask, jsonify

app = Flask(__name__)


@app.route("/hello", methods=["GET"])
def say_hello():
return jsonify({"msg": "Hello from Flask"})


if __name__ == "__main__":
# Please do not set debug=True in production
app.run(host="0.0.0.0", port=5000, debug=True)

Running the flask application:

(docker-env) dinesh@dinesh % python my_flask.py 
* Serving Flask app 'my_sync'
* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on all addresses (0.0.0.0)
* Running on http://127.0.0.1:5000
* Running on http://10.104.1.164:5000
Press CTRL+C to quit
* Restarting with stat
* Debugger is active!

Output:

{
"msg": "Hello from Flask"
}
Flask endpoint browser output

Now that our flask application is running and giving us the expected output, let us dockerise it.

Dockers — The what?

From the docs,

A container is a standard unit of software that packages up code and all its dependencies so the application runs quickly and reliably from one computing environment to another. A Docker container image is a lightweight, standalone, executable package of software that includes everything needed to run an application

https://www.docker.com/resources/what-container/

Technically, docker containers are an abstraction layer on top of your application. In our case the flask application. So what all do we need to run our flask application error-free on different environments? Let’s list them out.

  1. First and foremost, we need python.
  2. flask library should be installed.

Well, that is all we need. Let’s say you want your flask app to be shipped and run elsewhere on your peer’s machine all we need is a python environment with flask installed in it. That’s exactly the problem Docker solves.

You don’t have to provide your dependent libraries or a README document to your peer to get started with your flask app. All he/she needs is a docker environment to run your app and access to the repository where your app is hosted. We will use the dockerhub to host the flask app. However, most of the organisations use JFrog artifactory as well to host their internal docker images.

Dockerhub:

Docker Hub is a hosted repository service provided by Docker for finding and sharing container images with your team

Requirements.txt:

A requirements.txt file lists all the dependent libraries required to run your project. All we need is the flask module for our little workshop.

flask==2.2.2

Let’s write the Docker file.

Docker File:

FROM python:3.9-slim-buster
WORKDIR /app
COPY ./requirements.txt /app
RUN pip install -r requirements.txt
COPY . .
EXPOSE 5000
ENV FLASK_APP=my_flask.py
CMD ["flask", "run", "--host", "0.0.0.0"]
  1. Import python from dockerhub.
  2. Create a working directory app.
  3. Copy the requirements.txt file inside the app directory.
  4. Install all the dependencies from the requirements.txt file.
  5. Copy the entire app project into the app directory.
  6. We expose port 5000 as the app will run on port 5000.
  7. Define the FLASK_APP environment variable. Else the interpreter may complain it’s unable to find the variable
  8. Finally, type in the run command which is flask run --host 0.0.0.0. This is to ensure the server accepts requests from all hosts.

Building docker images:

Now that we have our Dockerfile ready, we will build the docker image. Please ensure that your docker desktop is running. Else you may get this error.

Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

Command:

(docker-env) dinesh@dinesh % docker build -t myflaskapp .

Please notice the period at the end of the command.

[+] Building 27.8s (10/10) FINISHED                                                                                                                                                                                     
=> [internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 37B 0.0s
=> [internal] load .dockerignore 0.0s
=> => transferring context: 2B 0.0s
=> [internal] load metadata for docker.io/library/python:3.9-slim-buster 3.8s
=> [1/5] FROM docker.io/library/python:3.9-slim-buster@sha256:e0bf67a281748c0f00c320dbe522631e92c649bef22a14f00a599c1981dac2a6 18.3s
=> => resolve docker.io/library/python:3.9-slim-buster@sha256:e0bf67a281748c0f00c320dbe522631e92c649bef22a14f00a599c1981dac2a6 0.0s
=> => sha256:e0bf67a281748c0f00c320dbe522631e92c649bef22a14f00a599c1981dac2a6 988B / 988B 0.0s
sha256:2238450926aa858e592e60bb5d68dd26eeab8a984eee45505ca89d2022e3b450 27.14MB / 27.14MB 16.1s
=> => sha256:15d04b3d1b9d2c709f48e1224daac0ab09f65130a892380cf1f725f980dbb0fa 2.78MB / 2.78MB 1.2s
=> => sha256:83de38ae3b75c524cce554598a0f0842ba782b433f637623bdcff1d4158c8764 11.57MB / 11.57MB 7.4s
=> => sha256:f2ae8a19c88b4a4fee41cd329b6cc78f34ea84933f26d82c5157971e4cc2f4dc 233B / 233B 4.5s
=> => 0.2s
=> [internal] load build context 0.0s
=> => transferring context: 87.10kB 0.0s
=> [2/5] WORKDIR /app 0.5s
=> [3/5] COPY ./requirements.txt /app 0.0s
=> [4/5] RUN pip install -r requirements.txt 5.0s
=> [5/5] COPY . . 0.0s
=> exporting to image 0.2s
=> => exporting layers 0.2s
=> => writing image sha256:6b1ab29f10db5c51a894504df7ac11594f5da5b1e9da68561c1e6543ff0fc7a8 0.0s
=> => naming to docker.io/library/myflaskapp

Once the image is successfully built, the images should be listed as part of your docker images.

(docker-env) dinesh@dinesh % docker imagesREPOSITORY    TAG       IMAGE ID       CREATED          SIZE
myflaskapp latest 6b1ab29f10db 10 minutes ago 133MB

Run the Docker image:

(docker-env) dinesh@dinesh % docker run -p 5000:5000 myflaskapp

* Serving Flask app 'my_flask.py'
* Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on all addresses (0.0.0.0)
* Running on http://127.0.0.1:5000
* Running on http://172.17.0.2:5000
Press CTRL+C to quit

Pushing the Docker image to Docker hub:

Docker images are pushed to Docker Hub through the docker push command. A single Docker Hub repository can hold many Docker images (stored as tags). To push images to Docker Hub, a repository should be available in your account. Let’s say my repository name is myflaskapp, the docker push command will look like,

docker push <username>/<reponame>:tagname

docker push dinesh/myflaskapp:mytag

Summary:

  • A container is a standard unit of software that packages up code and all its dependencies
  • A Docker container image is a lightweight, standalone, executable package of software that includes everything needed to run an application

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store