Dockerize your python/flask application

In this article, we’re going to run a simple python application on a flask web-server using docker. I’ll assume that you have some familiarity with docker and that you have docker installed and running. If not, visit this link to get set up. I’ll also assume that you have python3 installed on your local machine. If you don’t you can visit this link to get python3 downloaded and installed

Part 1: Setting up the flask app

First, let’s build a simple flask app and get it running locally without using docker. Make a new directory for this project and navigate to it in your terminal, then create the following files in this directory: and requirements.txt

Image for post
Image for post

Part 2: Dockerizing the flask application

Now that we have our hello world app up and running, let’s run it in a docker container. First, we’ll need a Dockerfile. This is essentially a blueprint of instructions for setting up the environment in which our flask application will run. We’ll use this Dockerfile to build a docker image, which we can run as a docker container.

  • Line 2 sets /app as the working directory inside our container. All commands run inside the container after this line will be run from this directory.
  • Line 3 copies the contents of our working directory on our host machine to the /app directory in the container
  • Line 4 runs the pip3 install -r requirements.txt command from the working directory in our container (which we set to /app on line 2). This will use our requirements.txt file to install our specified dependencies.
  • Line 5 exposes port 5000 in our docker container, so that it can accept traffic to our app on that port.
  • Line 6 executes our python code in to start up our flask webserver. This command will execute immediately after our container is built and run.
Image for post
Image for post

Professional Full Stack Web Developer and Backend/DevOps Engineer

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