0
0
DockerHow-ToBeginner · 3 min read

How to Create a Dockerfile for Flask: Simple Guide

To create a Dockerfile for a Flask app, start with a Python base image, copy your app files, install dependencies from requirements.txt, expose the port Flask uses, and set the command to run the app with flask run. This creates a containerized Flask app ready to run anywhere Docker is installed.
📐

Syntax

A typical Dockerfile for Flask includes these parts:

  • FROM: base image with Python
  • WORKDIR: sets working directory inside container
  • COPY: copies app files into container
  • RUN: installs Python dependencies
  • EXPOSE: opens the port Flask listens on
  • CMD: command to start the Flask app
dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 5000
CMD ["flask", "run", "--host=0.0.0.0"]
💻

Example

This example Dockerfile builds a container for a simple Flask app. It installs dependencies, copies the app code, exposes port 5000, and runs the app so it is accessible outside the container.

dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 5000
CMD ["flask", "run", "--host=0.0.0.0"]
Output
* Serving Flask app 'app' (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. * Debug mode: off * Running on all addresses (0.0.0.0) * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
⚠️

Common Pitfalls

Common mistakes when creating a Dockerfile for Flask include:

  • Not setting --host=0.0.0.0 in the flask run command, which makes the app inaccessible outside the container.
  • Forgetting to copy requirements.txt before running pip install, causing dependency installation to fail.
  • Not exposing the correct port (default Flask port is 5000).
  • Using the default Flask development server in production without a proper WSGI server.
dockerfile
Wrong:
CMD ["flask", "run"]

Right:
CMD ["flask", "run", "--host=0.0.0.0"]
📊

Quick Reference

Remember these key points when writing a Dockerfile for Flask:

  • Use a lightweight Python base image like python:3.11-slim.
  • Copy requirements.txt first to leverage Docker cache.
  • Install dependencies with pip install --no-cache-dir to keep image size small.
  • Expose port 5000 and run Flask with --host=0.0.0.0.

Key Takeaways

Always set Flask to run on 0.0.0.0 to allow external access from the container.
Copy requirements.txt before installing dependencies to optimize Docker build caching.
Expose port 5000 in the Dockerfile to match Flask's default port.
Use a slim Python base image to keep the Docker image lightweight.
Avoid running Flask's development server in production without a proper WSGI server.