DEV Community

lnoueryo
lnoueryo

Posted on

The process of setting up a Mysql container with Docker Desktop and connecting from the host machine

Docker Desktop version is 4.32.0

Get Mysql Image

There is a search bar at the header.
Input mysql and you will see a list containing mysql.
Click on it.
A search bar

A list containing mysql

You will see the Pull button and click it.
If you wanna pull the image via the terminal, use the following command:

docker pull {image_name}
Enter fullscreen mode Exit fullscreen mode

The Pull button

Set Up Environmental Variables

After the image is downloaded, go to the images page from the drawer and you will see the MySQL image listed.
Click the run buttn.

The MySQL image listed

In the Optional settings, input the values as below and click the Run button

The Optional settings

The command is as follows:

docker run --name mysql-container -e MYSQL_ROOT_PASSWORD=password -p 3306:3306 -d mysql:latest
Enter fullscreen mode Exit fullscreen mode

Connect To The Mysql Container From The Host Machine

You might think that you can connect with the following command:

mysql -u root -p
Enter fullscreen mode Exit fullscreen mode

But actually you can't.
The error message will be:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

I asked ChatGPT about the reason for the error and the answer is you need to add the host IP as below.

mysql -u root -p -h 127.0.0.1
Enter fullscreen mode Exit fullscreen mode

And now you can connect to it.
Thank You!!

Top comments (0)