Finn Finn - 7 months ago 128
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

/etc/mysql/my.cnf
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
docker-compose.yml


version: '2'
services:
mysqldb:
image: mysql:5.6
environment:
MYSQL_ROOT_PASSWORD: password
volumes:
- ./mysql-data:/var/lib/mysql
- ./mysql-import-data:/import-data
ports:
- "3333:3306"
blog:
image: webdevops/php-nginx:ubuntu-14.04
environment:
WEB_DOCUMENT_ROOT: /usr/share/nginx/html
volumes:
- ./blog:/usr/share/nginx/html
ports:
- "8080:80"
depends_on:
- 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

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 127.0.0.1 --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.

Comments