Home >Database >Mysql Tutorial >How Do I Connect to a Docker MySQL Container from My Host Machine?
Problem:
Establishing a connection to a MySQL instance running within a Docker container from the host system is proving unsuccessful, resulting in error 2002.
Dockerfile Details:
The Dockerfile employed includes the following configuration:
FROM ubuntu:14.04.3 RUN apt-get update && apt-get install -y mysql-server RUN grep -v bind-address /etc/mysql/my.cnf > temp.txt && mv temp.txt /etc/mysql/my.cnf EXPOSE 3306 CMD /etc/init.d/mysql start && tail -F /var/log/mysql.log
While the image initializes without issue, attempts to connect from the host using the command mysql -P 12345 -uroot result in the aforementioned error.
Solution:
Connection Specification:
To connect to the MySQL instance within the Docker container, it is necessary to provide the correct parameters when invoking the mysql command from the host:
mysql -h localhost -P 3306 --protocol=tcp -u root
Here, -h localhost specifies the host, -P 3306 designates the port (in this case, 12345), and --protocol=tcp indicates that the connection should be established via TCP/IP rather than a socket connection.
Socket Limitations:
Within the Docker container, MySQL binds to all network interfaces, excluding localhost. Since the host system cannot access the socket, it is essential to use TCP/IP for communication. By specifying --protocol=tcp in the mysql command, the connection establishes successfully through port 3306.
The above is the detailed content of How Do I Connect to a Docker MySQL Container from My Host Machine?. For more information, please follow other related articles on the PHP Chinese website!