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 docker-compose up, the dockerflaskexample container 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 this is so? Is it because mysql isn't ready when the webapp started?
depends_ononly waits for the database container to be started. Not for it to be ready.