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:
Create a health check script that will exit 1
when success: select 1+1 from <table>
or something. Call this health.sh
.
In your Dockerfile, copy health.sh
to the container.
HEALTHCHECK CMD
to run the health.sh
script.In your compose file, modify your app
definition:
version: 2.1 app: build: . links: - mysql depends_on: mysql: condition: service_healthy
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With