简体   繁体   中英

Using docker-compose Mysql + App

I am trying to link two containers using docker.

MySQL Dockerfile:

...
EXPOSE 3306
CMD ["/usr/sbin/mysqld"]

App Dockerfile:

...
ADD . /services
CMD ["python", "-u", "services/run_tests.py"]

In the run_tests.py i used

self.db = MySQLdb.connect(host="mysql", user="XYZ", passwd="XYZ", db="TEST_DB")

In my docker-compose.yml:

app:
   build: .
   links:
      - mysql
mysql:
   image: XYZ/KJM

When i run docker-compose up i could not connect to mysql container.

OperationalError: (2003, "Can't connect to MySQL server on 'rds' (111)")

EDIT: I dont know if i need to wait little to start the app docker. I imagine that the MySQL isnt up wheh the app try to connect.

This is a known issue and is yet to be addresses. Check out this link Docker services need to wait

You are absolutely right that the MySql service is not yet up while your App container comes up very quickly and hence when it tries to connect to MySql, the connection is refused. On the application side what you can do is that you could write some retry logic. Something on these lines

while(numberOfRetries > 0) {

try {

  // Try to connect to MySql
} catch(Exception e) {

     numberOfRetries--;

     if(numberOfRetries == 0)
       // log the exception 
}

Hope this helps.

Since Docker 1.13, this is now a solved problem. You can now use the HEALTHCHECK directive in your MySQL Dockerfile:

  1. Create a health check script that will exit 1 when success: select 1+1 from <table> or something. Call this health.sh .

  2. In your Dockerfile, copy health.sh to the container.

  3. Use the HEALTHCHECK CMD to run the health.sh script.
  4. In your compose file, modify your app definition:

    \nversion: 2.1 \n\napp: \n  build: . \n  links: \n    - mysql \n  depends_on: \n    mysql: \n      condition: service_healthy \n

I think you're right that you need to wait. You can attempt the connection in a loop, and retry a few times with a short sleep between each attempt.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM