Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker Mysql Can't connect to local MySQL server through socket

Tags:

docker

I'm using below command to run the mysql docker container.

docker container run -it --name mysql-test -e MYSQL_ROOT_PASSWORD=secret mysql bash

Then I tried to connect to mysql inside docker container using below command.

mysql -uroot -psecret

It gives me below error.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

If I do below then sometimes it works but not all time.

touch /var/run/mysqld/mysqld.sock

Then I tried to run the container in detach mode but it also gave me the same error.

docker container run -d -p 3306:3306 --name mysql-test -e MYSQL_ROOT_PASSWORD=secret mysql
docker exec -it mysql-test bash
mysql -uroot -p

What am I doing wrong here?

like image 625
jonarya Avatar asked Oct 17 '22 07:10

jonarya


2 Answers

If you happen to get “Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ (2)” errors in logging in to mysql-server while working on docker containers:

check the path of socket file in /etc/mysql/my.cnf

check if mysqld.sock and mysqld.pid file is present in /var/run/mysqld/ directory or not.

If not, create these files as:

touch /var/run/mysqld/mysqld.sock
touch /var/run/mysqld/mysqld.pid
chown -R mysql:mysql /var/run/mysqld/mysqld.sock
chown -R mysql:mysql /var/run/mysqld/mysqld.sock
chmod -R 644 /var/run/mysqld/mysqld.sock

Now restart the mysql-server as:

service mysql-server restart

Now, trying logging again in to mysql-server.

like image 110
Shubhankar Naik Avatar answered Nov 15 '22 07:11

Shubhankar Naik


This Connect to mysql in a docker container from the host may help.

  1. mysql command try to connect via mysqld.sock, but your mysql server are running inside a container, so no .sock file here. You can try to mount it to the host.
  2. you touch a .sock file, ofcourse it don't make any thing work, maybe you would like to understand what is a sock file :)
like image 33
Chân Nhân Pham Avatar answered Nov 15 '22 07:11

Chân Nhân Pham