Problem scenarios
Start a mysql container locally using docker and map the local port 33067 to mysql 3306 in the container. Assume that the container's ip address is 172.17.0.2, use the local mysql client to try to connect to the mysql service in the container.
Method 1
Because it is bound to the local port 33067, you can specify the port number during connection.
Mysql-uroot-P33067
In this case, the mysql-client actually enters the local mysql service and can be viewed using the status command.
Connection id: 49
Current database:
Current user: root @ localhost
SSL: Not in use
Current pager: stdout
Using outfile :''
Using delimiter :;
Server version: 5.5.52-0ubuntu0. 14.04.1 (Ubuntu)
Protocol version: 10
Connection: Localhost via UNIX socket
Server characterset: latin1
Db characterset: latin1
Client characterset: utf8
Conn. characterset: utf8
UNIX socket:/var/run/mysqld. sock
Uptime: 1 hour 35 min 41 sec
The tion information is a local unix socket. Such a connection is not connected to mysql in the container.
Method 2
Try to specify the corresponding host and the mapped local port. The host is localhost because it is mapped to the local port.
Mysql-uroot-hlocalhost-P33067
The local mysql service is still connected.
Method 3
Use the container ip address directly. The default port is 3306.
Mysql-uroot-h172.17.0.2
The connection is successful and enters the mysql service inside the container.
Method 4
Use the 127.0.0.1 address and specify the locally mapped Port 33067
Mysql-uroot-h127.0.0.1-P33067
The connection is successful and enters the mysql service inside the container.
Analysis
The host connected to methods 1 and 2 is actually localhost (no host is specified, the default is localhost). At this time, no matter what port is specified, mysql-client tries to use the unix socket communication method, that is, the local socket, so if you want to connect to the mysql service of the specified ip address, you must specify an ip address, even if the ip is mapped to localhost.
In the preceding scenario, because the mysql service port in the container is mapped to a specific local port, even in this case, the local ip address 127.0.0.1 must be specified for the connection, instead of the local hostname localhost, once localhost is used, mysql-client tries to use a local unix socket to connect to the local mysql service.
Therefore, we can know that the connection from mysql without specifying an ip address is localhost by default, and the connection is a local mysql service, no matter what the port is
Beware that by default, the mysql client tries to connect using a unix socket when you tell it to connect to localhost. So do use 127.0.0.1 and not localhost:
$ Mysql-h 127.0.0.1-P 3306-u root