DEV Community

Cover image for How to Dockerize a Flask App 🐳
Thesi
Thesi

Posted on

How to Dockerize a Flask App 🐳

Dockerizing a Flask app is a great way to make your app ready to be deployed on any cloud platform. Luckily, it's super easy to do. Lets get started!

The absolute easiest way to dockerize a flask app is to use the Dockerfile that we've provided below.

FROM python:3

COPY . .

RUN pip3 install -r requirements.txt

CMD [ "python3", "-m" , "flask", "run", "--host=0.0.0.0"]
Enter fullscreen mode Exit fullscreen mode

Buuuut, there is a lot of room for improvement. Lets go over some improvements and next steps together

Improvements

These are all super easy to do and will make your life easier, trust me!

Use a better python base image

The base image that we used is the latest version of python, which is great, but we can do better. Generally, you want to use specific versions of your base images to prevent any breaking changes.
Additionally, the normal python:3 image is huge at 1GB! We can do better, by simply using python:3.11-alpine3.20 for example. This image is only 64MB big!

FROM python:3.11-alpine3.20
Enter fullscreen mode Exit fullscreen mode

Improve the caching

Right now we copy everything into the image at once. While this is super easy, it's not very efficient. We can do better by copying the requirements first, installing the dependencies and then copying the rest of the app.

COPY requirements.txt requirements.txt

RUN pip3 install -r requirements.txt

COPY . .
Enter fullscreen mode Exit fullscreen mode

This will allow the dependencies to be cached and not re-installed on every build! Subsequent builds will be a lot faster πŸš€.

Use a working directory

This is really more of a personal preference, but I prefer to have the working directory set to /app. This is the standard working directory for most apps and it's easy to remember.

WORKDIR /app
Enter fullscreen mode Exit fullscreen mode

You dont just put all of your app code into your documents folder, do you? So why would you do that in a Docker image? :D

Final Dockerfile

The final Dockerfile should look like this:

FROM python:3.11-alpine3.20

WORKDIR /app

COPY requirements.txt requirements.txt

RUN pip3 install -r requirements.txt

COPY . .

CMD [ "python3", "-m" , "flask", "run", "--host=0.0.0.0"]
Enter fullscreen mode Exit fullscreen mode

Simply build it using docker build . -t flask-app and run it using docker run -p 5050:5050 flask-app! πŸŽ‰

Next Steps

At this poing you probably want to either push it to a Docker Registry or host it somewhere.

I work for Sliplane, a Docker hosting platform that makes it super easy to host your Docker apps. Check it out, the first 2 days are on me:)

Top comments (0)