Agentic AI with Java: Live Cohort
DockerDockerizing Applications

Dockerizing A Basic Python Flask Application

Create a Docker image for a simple Flask application and run it with port mapping.

Python Flask applications are straightforward to dockerize.

The image needs Python, application files, dependencies from requirements.txt, and a command to start the Flask app.

Example project

flask-app/
  app.py
  requirements.txt
  Dockerfile

requirements.txt:

flask

Simple app.py:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Hello from Flask in Docker"

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)

The host must be 0.0.0.0 so the app can accept traffic from outside the container.

Dockerfile

FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 5000
CMD ["python", "app.py"]

Build and run

docker build -t flask-app:1.0 .
docker run -d -p 5000:5000 --name flask-web flask-app:1.0

Open:

http://localhost:5000

Common Flask mistake

If Flask runs only on 127.0.0.1, it listens inside the container only.

Use:

app.run(host="0.0.0.0", port=5000)

This allows Docker port mapping to reach it.

For web apps inside containers, the app should listen on 0.0.0.0, and Docker should map the container port to a host port.

Written By: Shiva Srivastava

How is this guide?

Last updated on