1

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?

4
  • It sounds like a timing issue. MySQL needs some time to get ready to accept connections, so if you try to connect immediately, it'll refuse the connection. depends_on only waits for the database container to be started. Not for it to be ready. Commented Apr 2, 2024 at 8:17
  • This might help solve it: stackoverflow.com/questions/42567475/… Commented Apr 2, 2024 at 8:18
  • you can add timeout in your container, moreover, you can add a health check to your database container also. adding health check to your db coriander makes sense. Commented Apr 2, 2024 at 10:25
  • Docker Compose wait for container X before starting Y also discusses this startup-order problem. Commented Apr 2, 2024 at 10:30

1 Answer 1

0

Thank you all for suggestions!

I changed my docker-compose like this and it worked:

version: '3.4' services: dockerflaskexample: image: dockerflaskexample build: context: . dockerfile: ./Dockerfile ports: - 5002:5002 volumes: - app_code:/app depends_on: mysql: condition: service_healthy 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" healthcheck: test: ["CMD", "mysqladmin" ,"ping", "-h", "localhost"] timeout: 20s retries: 10 volumes: mysql_data: app_code: 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.