Building Docker Image for an existing Flask project

Aayush Bajaj
Quick Hacks
Published in
2 min readJan 15, 2021

You can start by setting up a virtual environment in Python with all dependencies required to run the project seamlessly. This is the first step and kind of crucial so if you don’t have a virtual environment set head over to python-venv to set it right up. After installing all the dependencies, using pip, run:

pip freeze > requirements.txt

This will make a requirements.txt file in that dir containing all the dependencies with their versions you used to run your project. This step is important since Docker Image is a snapshot of your running env. After successfully creating venv and requirements file create a DOCKERFILE in the project dir.

Line 1: Get an image of ubuntu:18.04 from the docker-hub
Line 3: Specify a working directory. Note that all the commands like COPY, RUN will be executed in this.
Line 5-6: Installing the python development files and updating the system.
Line 8: Copy the requirements file from the current directory to the WORKDIR of the docker image.
Line 10: executing the pip install on the requirements file.
Line 12: Copy the rest of the code file to the WORKDIR
Line 14-16: Execute the index.py (Flask server file) upon entry.

Now run the following command to build the image:

docker build -t <Image name>:latest .

What this will do is execute the DOCKERFILE that contains all the instructions to build an image. Don’t forget to replace <> with your name of the image. This command will take a while to run.

After this, you have to create a container of the image which will run your project. To create a container run:

docker run --name <container name> -v "$(pwd)":/home -p5000:5000 <image name>:latest

This will make a container of that image and your Flask server will be up.

Tip: Make your Flask server to point to 0.0.0.0:port instead of 127.0.0.1

--

--

Aayush Bajaj
Quick Hacks

ML Engineer who writes about how machines will take over the world.