Welcome to this interactive Docker Compose tutorial! Learn how to containerize a Flask application
with Docker Compose through hands-on examples. Click the copy buttons to grab the code snippets.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello from Flask! (Containerized with Docker Compose)'
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
requirements.txt
flask
Dockerfile
# Use an official Python runtime as a parent image
FROM python:3.9-slim-buster
# Set the working directory in the container
WORKDIR /app
# Copy the requirements file into the working directory
COPY requirements.txt .
# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
# Copy the rest of the application code into the working directory
COPY . .
# Make port 5000 available to the world outside this container
EXPOSE 5000
# Run app.py when the container launches
CMD ["python", "app.py"]
docker-compose.yml
version: '3.8' # Specify the Docker Compose file format version
services:
flask_app:
build: ./app # Build the Docker image for 'flask_app' from the 'app' directory
ports:
- "5000:5000" # Map port 5000 on the host to port 5000 in the 'flask_app' container
volumes:
- ./app:/app # Mount the local 'app' directory into the container for live updates (optional but very useful for development)
restart: on-failure # Restart the container if it exits due to an error