Home > Database > Mysql Tutorial > How to Connect to a MySQL Docker Container from Your Host Machine?

How to Connect to a MySQL Docker Container from Your Host Machine?

Linda Hamilton
Release: 2024-12-09 15:34:11
Original
517 people have browsed it

How to Connect to a MySQL Docker Container from Your Host Machine?

Connecting to MySQL in a Docker Container

Problem:

You want to connect to a MySQL instance running in a Docker container from your host machine, but you're encountering an error related to the socket connection.

Dockerfile Configuration

Your Dockerfile includes the following changes:

  • Updates and installs MySQL-server
  • Removes the bind-address restriction in my.cnf
  • Exposes port 3306

Successful Command Sequence:

  1. Build the image: docker build -t my-image .
  2. Run the container: docker run -d -p 12345:3306 my-image

Connecting from Within the Container:

Once inside the container, you can successfully connect to MySQL using: mysql -u root

Unsuccessful Attempt from Host Machine:

When attempting to connect from the host using: mysql -P 12345 -uroot, you receive an error indicating the inability to connect to MySQL through the socket.

Solution:

To connect to the MySQL instance in the Docker container from the host machine, use the following command:

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

Replace 3306 with the port number you have forwarded from the Docker container (in this case, 12345).

Explanation:

Since MySQL is running within the Docker container, the socket connection is not available. By setting "--protocol=tcp" in the mysql command, you can specify that the connection should be made through TCP instead.

The above is the detailed content of How to Connect to a MySQL Docker Container from Your 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