I’m trying to run Docker + Flask + MySQL, and here is my docker-compose.yaml
:
services:
dockerflaskexample:
image: dockerflaskexample
build:
context: .
dockerfile: ./Dockerfile
ports:
- 5002:5002
volumes:
- app_code:/app
depends_on:
- mysql
container_name: dockerflaskexample
mysql:
image: mysql:latest
restart: always
environment:
MYSQL_ROOT_PASSWORD: webapp-db-root-password
MYSQL_DATABASE: webapp-db
MYSQL_USER: webapp-db-user
MYSQL_PASSWORD: webapp-db-password
volumes:
- mysql_data:/var/lib/mysql
ports:
- "3306:3306"
volumes:
mysql_data:
app_code:
… and in __init__.py
:
# Establishing a connection to the MySQL database
connection = pymysql.connect(
host='mysql',
database='webapp-db',
user='webapp-db-user',
password='webapp-db-password',
port=3306,
charset='utf8mb4', # adjust charset if necessary
)
After I compose up, container dockerflaskexample
always fails with the following error:
2024-04-02 16:25:05 pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'mysql' ([Errno 111] Connection refused)")
However, if I simply run the Exited (3)
container again, it works.
May I know why is it so? Is it because mysql
isn’t ready when the webapp started?
2
Answers
Your intuition is correct(you need to wait for the database to start). You can wait either using Docker Compose or using Python.
Although it’s waiting for a rabbitMQ service, the Docker Compose solution is stated here. You need a different
healthcheck
for the mysql service configuration:If you prefer to use Python, you can easily create the retry logic as described here.
It seems issue due to networks. You are trying to use
host
as thecontainer_name
this requires adding both containers to the same network. The network can be defined at the bottom of the.yml
file (It can be external as well).Please check the example.
also check – https://docs.docker.com/compose/networking/#specify-custom-networks