Slow connection to mysql running in docker

4.4k views Asked by At

I installed a docker image for mysql.

docker run --name mysql -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD="Foo" -e DB_REMOTE_ROOT_NAME=root -e DB_REMOTE_ROOT_PASS="foo" -e DB_USER=foo -e DB_PASS="foo" -e DB_NAME=foo -v /:/host -v /home/user1/data/mysql:/var/lib/mysql mysql:latest

Everything is good and I can connect to mysql in two ways

docker exec -it mysql bash
mysql -ufoo -pfoo foo

and from my mac console as well (without docker exec -it)

mysql -ufoo -pfoo -h0.0.0.0 foo

The problem I see is that the second approach it takes a long time to connect. it connects successfully but there is like a delay of 15 to 20 seconds.

whereas in docker exec it connects instantaneously.

why is there a delay when i connect from my mac terminal directly using mysql rather than first SSH into the box?

I tried to replace 0.0.0.0 with localhost. but then I get an error

mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

Edit::

I tried the following and nothing really works

mysql -ufoo -pbar -h1x.1x.5x.14x foo
mysql -ufoo -pbar -h127.0.0.1 foo
mysql -ufoo -pbar -hmysql.local foo

all the 3 above have a 10 second delay

But if I do

docker exec -it mysql bash
mysql -ufoo -pbar foo

this is instantaneous with no delay

2

There are 2 answers

4
Eugen Mayer On

why are you using 0.0.0.0? it might be, that it is trying to connect using a socket first, due to localhost-binding (mysql-client behaviors).

  1. Try localhost/127.0.0.1 if you are using docker-for-mac
  2. try to put something like 127.0.0.1 test.local into your /etc/hosts file to and the use -htest.local - does this connect faster?
  3. Does your mysql-container use "dns resolving"? is it faster when you use skip-name-resolve in your /etc/mysql/my.ini ? ( could be related to a also ) if not related to a, check if the mysql container has a broken DNS
3
Mark On

I had this issue on centos linux. The problem seems to be related to name resolution. I resolved this issue in my case by adding the mysql flag --skip-name-resolve. In my case it reduced connection time from ~20 seconds to less than 1 second.

Based on your command line I think this should work:

docker run --name mysql -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD="Foo" \
-e DB_REMOTE_ROOT_NAME=root -e DB_REMOTE_ROOT_PASS="foo" -e DB_USER=foo \
-e DB_PASS="foo" -e DB_NAME=foo \
-v /:/host -v /home/user1/data/mysql:/var/lib/mysql mysql:latest --skip-name-resolve