...

/

Database and Core App Connection through Docker

Database and Core App Connection through Docker

Learn how to connect the Flask application to MySQL database through Docker.

Adding the database to the docker-compose.yml file

To connect our Core app to the database, we must add the MySQL database as a service in the docker-compose.yml file, as shown below:

Press + to interact
version: '2.2'
services:
backend:
image: educative1/python_django_flask:latest
command: 'python3 core.py'
ports:
- 5000:5000
volumes:
- .:/backendservice
depends_on:
db:
condition: service_healthy
db:
image: mysql:latest
restart: always
environment:
MYSQL_DATABASE: core
MYSQL_USER: microservice
MYSQL_PASSWORD: microservice
MYSQL_ROOT_PASSWORD: microservice
volumes:
- dbdata:/var/lib/mysql
ports:
- 3306:3306
healthcheck:
test: mysqladmin ping -h 127.0.0.1 -u $$MYSQL_USER --password=$$MYSQL_PASSWORD
volumes:
dbdata:
  • Lines 10–11: We use the depends_on keyword to set the startup or shutdown order of services. Here, we set it to db. This means the database service will be the first to start running, before any other service.

  • Line 12: We use the condition keyword to state the condition under which dependency is satisfied. Here, it is  ...