When developing web applications, we often encounter a problem: “Why does my code run fine locally but fail on the server?” This is usually due to differences between the development and production environments, such as Python version, dependency library versions, and system configurations. Docker containerization technology can perfectly solve this problem, allowing your Flask application to “work out of the box” in any Docker-supported environment.
Why Choose Docker Containerization?¶
Traditional deployment requires manually configuring the Python environment, installing dependencies, and starting services on the server, which is error-prone and hard to reproduce. Docker containerization is like packaging an application with a “complete operating system snapshot.” As long as the Docker environment is consistent, the application will run the same way on development machines, servers, or cloud platforms.
Core Advantages:
- Environment Consistency: Development, testing, and production environments are identical, avoiding the “it works on my machine” problem.
- Isolation: Containers are isolated from each other and do not interfere.
- Lightweight: Containers consume fewer resources compared to virtual machines.
- Quick Deployment: A single command can start the entire application stack.
Quick Start: Dockerize Your First Flask App¶
Step 1: Prepare the Flask App¶
First, create the simplest Flask application. Create app.py:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello, Dockerized Flask App!"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
Create requirements.txt (list dependencies):
Flask==2.3.3
Step 2: Write the Dockerfile¶
Create Dockerfile (no extension) in the project root directory with the following content:
# Base image: Use the official Python 3.9 slim version (smaller image size)
FROM python:3.9-slim
# Set working directory (default path after entering the container)
WORKDIR /app
# Copy dependency files to the container
COPY requirements.txt .
# Install dependencies (--no-cache-dir to avoid cache space usage)
RUN pip install --no-cache-dir -r requirements.txt
# Copy current directory files to the container working directory
COPY . .
# Set environment variables: specify Flask entry file and running environment
ENV FLASK_APP=app.py
ENV FLASK_ENV=production
# Expose the 5000 port inside the container (declarative, actual mapping required at runtime)
EXPOSE 5000
# Start command: run the Flask application
CMD ["flask", "run", "--host=0.0.0.0"]
Step 3: Build the Docker Image¶
Execute the following command in the project directory to build the image (. represents the current directory, note the trailing dot):
docker build -t myflaskapp .
-t myflaskapp: Tag the image (myflaskappis the image name, customizable)docker build: Tells Docker to build the image based on the Dockerfile
After successful build, check the image list with docker images and find the myflaskapp image.
Step 4: Run the Docker Container¶
Start the container using the built image:
docker run -p 5000:5000 myflaskapp
-p 5000:5000: Map port 5000 inside the container to port 5000 on the local machine- Access
http://localhost:5000to see the Flask app return “Hello, Dockerized Flask App!”
Step 5: Stop the Container¶
Press Ctrl+C to stop the container. To run in detached mode (background), add the -d parameter:
docker run -d -p 5000:5000 --name myflaskcontainer myflaskapp
To stop a running container:
docker stop myflaskcontainer # Stop the container
docker rm myflaskcontainer # Remove the stopped container (optional)
Advanced Tips: Professional Deployment¶
1. Optimize Image Size (Multi-stage Builds)¶
The previous Dockerfile uses a base image directly, which may result in a larger image. Reduce the image size with multi-stage builds:
# Stage 1: Build stage
FROM python:3.9-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip wheel --no-cache-dir --no-deps --wheel-dir /app/wheels -r requirements.txt
# Stage 2: Runtime stage
FROM python:3.9-slim
WORKDIR /app
COPY --from=builder /app/wheels /wheels
RUN pip install --no-cache /wheels/*
COPY . .
ENV FLASK_APP=app.py
EXPOSE 5000
CMD ["flask", "run", "--host=0.0.0.0"]
2. Data Persistence (Avoid File Loss)¶
If your app needs to save user uploads or database data, use Docker volume mounts:
# Create a data volume
docker volume create flask_data
# Run the container with volume mounting (map container's /app/data to the volume)
docker run -d -p 5000:5000 -v flask_data:/app/data myflaskapp
3. Environment Variable Management (No Hardcoded Sensitive Info)¶
Create a .env file (do not commit to the code repository):
FLASK_SECRET_KEY=your_secret_key_here
DATABASE_URI=sqlite:////app/data/db.sqlite
Reference environment variables in Dockerfile:
# Set default environment variables in Dockerfile (for development)
ENV FLASK_APP=app.py
ENV FLASK_ENV=production
# Override at runtime with -e parameter
docker run -e FLASK_SECRET_KEY=prod_key -p 5000:5000 myflaskapp
Summary¶
Docker containerization for Flask applications eliminates the “environment dependency” problem. The core process is: Write Dockerfile → Build Image → Run Container. With techniques like multi-stage builds, data volumes, and environment variables, deployment becomes more stable and secure.
Must-Try for Beginners: Package your own Flask app with Docker and experience the joy of “build once, run anywhere”!
Common Questions & Answers¶
-
Q: How to view container logs?
A:docker logs [container ID or name] -
Q: How to redeploy after code changes?
A: Rebuild the image:docker build -t myflaskapp ., then restart the container -
Q: No Docker Desktop?
A: Windows/Mac need to install Docker Desktop, Linux users can refer to the official docs to install the Docker engine
With Docker containerization, your Flask app gains the ability to “package once, run anywhere,” significantly improving deployment efficiency and stability!