Project-06: Building a Two-Tier Flask App with Docker Compose
Prerequisites
Make sure you have Docker and Docker Compose installed on your machine.
Step 1: Create Your Docker Compose File
The Docker Compose file is the backbone of our setup. It defines two services: mysql
and flask-app
. Here’s the file:
version: "3.9"
services:
mysql:
image: mysql:5.7
container_name: mysql-container
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: devops
MYSQL_USER: admin
MYSQL_PASSWORD: admin
volumes:
- ./mysql-data:/var/lib/mysql
- ./message.sql:/docker-entrypoint-initdb.d/message.sql
networks:
- twotier
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-uroot", "-proot"]
interval: 10s
timeout: 5s
retries: 5
start_period: 60s
flask-app:
build:
context: .
container_name: flaskapp-container
ports:
- "5000:5000"
environment:
MYSQL_HOST: mysql
MYSQL_USER: root
MYSQL_PASSWORD: root
MYSQL_DB: devops
depends_on:
- mysql
networks:
- twotier
restart: always
healthcheck:
test: ["CMD-SHELL", "curl -f http://localhost:5000/health || exit 1"]
interval: 10s
timeout: 5s
retries: 5
start_period: 30s
networks:
twotier:
Key Components
MySQL Service:
We mount
mysql-data
to/var/lib/mysql
to ensure data persistence.A health check is set up to verify that the MySQL service is ready.
Flask App Service:
This service builds from a Dockerfile located in the same directory (
.
).We expose port
5000
for Flask's default port.Environment variables point to the
mysql
service for database connectivity.MYSQL_HOST: mysql
will allow yourflask-app
service to correctly connect to the MySQL database.It depends on the
mysql
service, so the Flask app will only start once MySQL is healthy.
Networks:
- Both services are connected to a custom network called
twotier
for internal communication.
- Both services are connected to a custom network called
Step 2: Build and Run the Application
Navigate to the directory containing your docker-compose.yml
file and run:
docker compose up
This command builds the Flask app image and starts the MySQL and Flask containers.
Step 3: Test and Verify
Once your services are up, you can test the application by visiting http://localhost:5000
on your browser. Check the health checks to ensure both MySQL and the Flask app are functioning correctly.
here is the link to github repo two-tier-flask-app
Subscribe to my newsletter
Read articles from Pakeeza Saeed directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by