Home > Database > Mysql Tutorial > How to Connect to a Dockerized MySQL Instance from the Host Machine?

How to Connect to a Dockerized MySQL Instance from the Host Machine?

Barbara Streisand
Release: 2024-11-29 08:39:11
Original
311 people have browsed it

How to Connect to a Dockerized MySQL Instance from the Host Machine?

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
Copy after login

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:

  1. Specify the host address as 'localhost'.
  2. Specify the port that the Docker MySQL instance is listening on (3306 by default).
  3. Set the protocol to 'tcp' as the Docker MySQL instance is not accessible via a Unix socket.

Command for Host Connection:

mysql -h localhost -P 3306 --protocol=tcp -u root
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template