Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 474
p.magalhaes Avatar asked Oct 19 '22 23:10

p.magalhaes


2 Answers

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.

like image 156
Sachin Malhotra Avatar answered Oct 21 '22 15:10

Sachin Malhotra


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:

    version: 2.1
    
    app:
      build: .
      links:
        - mysql
      depends_on:
        mysql:
          condition: service_healthy
    
like image 37
Daniel van Flymen Avatar answered Oct 21 '22 15:10

Daniel van Flymen