Connecting to MySQL in a Docker Container from the Host
Problem Description:
When trying to connect to a MySQL database running in a Docker container from the host machine, an error message is encountered: "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'".
Dockerfile:
The following Dockerfile is used to create the MySQL container:
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
Failed Attempts:
Despite successfully starting the MySQL instance within the container, connecting to it from the host with mysql -P 12345 -uroot results in the socket error.
Solution:
To connect to the MySQL database running in the Docker container from the host machine, the following steps are necessary:
Command for Host Connection:
mysql -h localhost -P 3306 --protocol=tcp -u root
Changing the Port:
If a different port is used to expose the MySQL instance in the Docker container (e.g., 12345), it should be specified in the connection command as well:
mysql -h localhost -P 12345 --protocol=tcp -u root
The above is the detailed content of How to Connect to a Dockerized MySQL Instance from the Host Machine?. For more information, please follow other related articles on the PHP Chinese website!