connect to mysql which is running in docker

2019-08-30 01:36发布

问题:

I ran my mysql in a docker container after making a docker network.

docker network create --subnet=172.19.0.0/16 network-name

docker run -p 3306:3306 --net network-name --ip 172.19.0.13 -e MYSQL_ROOT_PASSWORD=password -d

Then when I tried to connect to mysql in my local with command mysql -uroot -p, I got error (Error 2002 (HY000): Can't Connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2))

Then I succeeded with command mysql -u root -p -h 172.19.0.13

I thought I connected my localhost port 3306 with docker container's 3306 port. Why can't I connect to mysql through localhost port?

回答1:

you can connect to mysql by using a tcp socket or a unix socket . When you are remote you always use tcp socket . When you are local mysql client prefer socket .

In your case your need to know where mysql is the unix socket . you can use :

 netstat -npl

When mysql run in a docker container , you must be inside the container to have the ability to connect on localhost .

if you are local:

  • mysql -u root -p -h 127.0.0.1 will force usage of a tcp socket
  • mysql -u root -p -h localhost will use a unix socket


标签: mysql docker