Finn Finn - 1 year ago 361
SQL Question

Connect to mysql inside docker

I'm using the official MySQL image from docker hub and expose ports 3333:3306 to connect from outside.

I know that I have to change the bind IP inside

to the IP of this container and grant permission for a user like:
GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'container_ip';
so I can connect to this container by:

mysql -h container_ip -u root -p

But I received this error

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

Btw, I also try to connect from WordPress in another container but it cannot establish the connection. Here is

version: '2'
image: mysql:5.6
- ./mysql-data:/var/lib/mysql
- ./mysql-import-data:/import-data
- "3333:3306"
image: webdevops/php-nginx:ubuntu-14.04
WEB_DOCUMENT_ROOT: /usr/share/nginx/html
- ./blog:/usr/share/nginx/html
- "8080:80"
- mysqldb

  1. What's the mistake I made with this mysql container? I cannot connect to it.

  2. The IP of the container may change every time
    docker-compose up
    . How can I configure it?

Answer Source

Hmm I'm a little confused. From the point of view of the host os, the docker container is bound to one or more network interfaces on the host os. In your compose file you are exposing port 3333 to the host. That's what you have to connect to.

Plus you need to use an IP address, otherwise the mysql client will try to connect with a unix socket.

mysql -h --port 3333 -u root -p

If you are trying to connect from inside your blog container then you can use mysqldb as your host with the 3306 port.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download