17

I am reading the docs here and I find myself a bit confused, since running
docker run --name some-mysql -p 3306:3306 -d mysql

or

docker run --name some-mysql -p 127.0.0.1:3306:3306 -d mysql

then mysql --host localhost --port 3306 -u root gives me the following error :

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

But running mysql -u root -p --host 0.0.0.0 works.

Does someone have an explanation ?

Rao
  • 20,781
  • 11
  • 57
  • 77
Aymeric R.
  • 301
  • 1
  • 2
  • 5
  • 1
    https://stackoverflow.com/questions/8348506/grant-remote-access-of-mysql-database-from-any-ip-address – Rao Oct 31 '17 at 00:59
  • 3
    This looks like a duplicate of [MySQL localhost / 127.0.0.1 problem](https://stackoverflow.com/questions/5239376/mysql-localhost-127-0-0-1-problem/) (especially Xiaofeng Tang's answer). – Gordon Davisson Oct 31 '17 at 01:07
  • Oh, I didn't realize the problem was from MySQL and not Docker. Thanks all for the help ! – Aymeric R. Oct 31 '17 at 11:35

2 Answers2

29

With docker port forwarding, there are two network namespaces you need to keep track of. The first is inside your container. If you listen on localhost inside the container, nothing outside the container can connect to your application. That includes blocking port forwarding from the docker host and container-to-container networking. So unless your container is talking to itself, you always listen on 0.0.0.0 with the application you are running inside the container.

The second network namespace is on your docker host. When you forward a port with docker run -p 127.0.0.1:1234:5678 ... that configures a listener on the docker host interface 127.0.0.1 port 1234, and forwards it to the container namespace port 5678 (that container must be listening on 0.0.0.0). If you leave off the ip, docker will publish the port on all interfaces on the host.

So when you configure mysql to listen on 127.0.0.1, there's no way to reach it from outside of the container's networking namespace. If you need to prevent others outside of your docker host from reaching the port, configure that restriction when publishing the port on the docker run cli.

Alireza
  • 10,237
  • 6
  • 43
  • 59
BMitch
  • 231,797
  • 42
  • 475
  • 450
3

As described in the mysql documentation (https://dev.mysql.com/doc/refman/5.7/en/connecting.html), when you connect to 127.0.0.1 with the client, it'll try to use the unix sockets to perform this operation. Normally this would work fine since it's on the same host. In Docker the socket file is not available.

Stefano
  • 4,730
  • 1
  • 20
  • 28