Flask + MySQL with Docker Compose
This guide shows how to set up a Flask application with MySQL database using Docker Compose.
1. Project Structure
flask-mysql-app/
│── docker-compose.yml
│── flask-app/
│ ├── Dockerfile
│ ├── requirements.txt
│ ├── app.py
2. docker-compose.yml
version: "3.9"
services:
flask-web:
build: ./flask-app
container_name: flask-web
ports:
- "5000:5000"
environment:
- DB_HOST=mysql-db
- DB_USER=root
- DB_PASSWORD=rootpassword
- DB_NAME=testdb
depends_on:
- mysql-db
networks:
- app-network
mysql-db:
image: mysql:8.0
container_name: mysql-db
restart: always
environment:
MYSQL_ROOT_PASSWORD: rootpassword
MYSQL_DATABASE: testdb
ports:
- "3306:3306"
volumes:
- mysql_data:/var/lib/mysql
networks:
- app-network
volumes:
mysql_data:
networks:
app-network:
driver: bridge
3. flask-app/Dockerfile
# Use official Python image
FROM python:3.11-slim
# Set working directory
WORKDIR /app
# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy app code
COPY . .
# Expose port 5000
EXPOSE 5000
# Run the application
CMD ["python", "app.py"]
4. flask-app/requirements.txt
flask
mysql-connector-python
5. flask-app/app.py
from flask import Flask, jsonify
import mysql.connector
import os
app = Flask(__name__)
# Read DB configs from environment variables
db_config = {
'host': os.getenv("DB_HOST", "localhost"),
'user': os.getenv("DB_USER", "root"),
'password': os.getenv("DB_PASSWORD", "rootpassword"),
'database': os.getenv("DB_NAME", "testdb")
}
@app.route('/')
def hello_world():
return "Hello from Flask + MySQL in Docker!"
@app.route('/users')
def get_users():
try:
conn = mysql.connector.connect(**db_config)
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50))")
cursor.execute("INSERT INTO users (name) VALUES ('Santosh'), ('Amit'), ('Priya')")
conn.commit()
cursor.execute("SELECT * FROM users")
result = cursor.fetchall()
cursor.close()
conn.close()
return jsonify(result)
except Exception as e:
return jsonify({"error": str(e)})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
6. Run the Setup
Build and start services:
docker-compose up --build
Access Flask app:
- Open: http://localhost:5000 →
"Hello from Flask + MySQL in Docker!"
- Open: http://localhost:5000/users → returns user list from MySQL DB.
👉 This setup proves portability:
- You can run it on any system with Docker & Docker Compose.
- It ships Flask + MySQL together, fully isolated in containers.
- No manual installation of Python/MySQL needed.
Top comments (0)