0
0
Flaskframework~5 mins

Docker containerization in Flask

Choose your learning style9 modes available
Introduction

Docker containerization helps you package your Flask app with everything it needs to run. This makes it easy to share and run your app anywhere without setup problems.

You want to share your Flask app with others and ensure it runs the same on their computers.
You need to deploy your Flask app to a server or cloud without worrying about missing software.
You want to test your Flask app in a clean environment that matches production.
You want to run multiple Flask apps on the same machine without conflicts.
You want to simplify updating your Flask app by replacing containers.
Syntax
Flask
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt ./
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "app.py"]

FROM sets the base image with Python installed.

WORKDIR sets the folder inside the container where commands run.

Examples
Basic Dockerfile to run a Flask app named app.py.
Flask
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt ./
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "app.py"]
Installs Flask directly without a requirements file.
Flask
FROM python:3.12-slim
WORKDIR /app
COPY . .
RUN pip install flask
CMD ["python", "app.py"]
Adds EXPOSE 5000 to tell Docker the app listens on port 5000.
Flask
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt ./
RUN pip install -r requirements.txt
COPY . .
EXPOSE 5000
CMD ["python", "app.py"]
Sample Program

This Dockerfile and Flask app show how to containerize a simple Flask app. The app listens on all network interfaces so Docker can route requests. Port 5000 is exposed for access.

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

# 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)
OutputSuccess
Important Notes

Always set host='0.0.0.0' in app.run() so the Flask app is reachable outside the container.

Use EXPOSE in the Dockerfile to document which port your app uses.

Keep your dependencies in requirements.txt for easy installation.

Summary

Docker packages your Flask app and its environment into a container.

This makes your app easy to run anywhere without setup issues.

Use a Dockerfile to define how to build and run your Flask app container.