Docker Community Forums

Share and learn in the Docker community.

Container fails to find mysql link if run in a shell script


(Mark Sta Ana) #1

I’ve got the following containers started

foo-mysql-data - data container for mysql
foo-mysql - mysql server

If I run docker command in a shell it works:

docker run -it --rm --link foo-mysql:mysql mysql:5.6 /bin/bash -c 'mysqladmin --host=mysql --password=$MYSQL_ENV_MYSQL_ROOT_PASSWORD create wordpress'

If I stick the same command in a shell script I get the following error:

Error follows:
Warning: Using a password on the command line interface can be insecure.
mysqladmin: connect to server at 'mysql' failed
error: 'Can't connect to MySQL server on 'mysql' (111)'
Check that mysqld is running on mysql and that the port is 3306.
You can check this by doing 'telnet mysql 3306'

I can get it to work in a shell script, by sticking a sleep before the command:

docker run -it --rm --link foo-mysql:mysql mysql:5.6 /bin/bash -c 'sleep 10 && mysqladmin --host=mysql --password=$MYSQL_ENV_MYSQL_ROOT_PASSWORD create wordpress'

I’d like to know why the sleep is necessary in a shell script.

For completeness sake here’s a test script (source):

#!/bin/bash

echo Creating MySQL data container
docker create --name foo-mysql-data -v /var/lib/mysql mysql:5.6

echo 'Creating MySQL server container'
docker run --name foo-mysql --volumes-from foo-mysql-data -e MYSQL_ROOT_PASSWORD=password -d mysql:5.6

echo 1st attempt to create database, will fail without sleep

docker run -it --rm --link foo-mysql:mysql mysql:5.6 /bin/bash -c 'mysqladmin --host=mysql --password=$MYSQL_ENV_MYSQL_ROOT_PASSWORD create wordpress'

echo 2nd attempt to create database, will pass with sleep
docker run -it --rm --link foo-mysql:mysql mysql:5.6 /bin/bash -c 'sleep 10 && mysqladmin --host=mysql --password=$MYSQL_ENV_MYSQL_ROOT_PASSWORD create wordpress'