8

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?

jonarya
  • 303
  • 1
  • 4
  • 16
  • 2
    Possible duplicate of [Installing MySQL in Docker fails with error message "Can't connect to local MySQL server through socket"](https://stackoverflow.com/questions/23234379/installing-mysql-in-docker-fails-with-error-message-cant-connect-to-local-mysq) – paulsm4 Feb 10 '19 at 07:26
  • @paulsm4 i'm not connecting remotely. i'm connecting with same container. – jonarya Feb 10 '19 at 07:29
  • Read ... the ... responses. *All* the responses. – paulsm4 Feb 10 '19 at 07:31
  • Are you trying to connect mysql installed on local from inside the docker? If so, have you used -v /var/run/mysqld/mysqld.sock:/var/run/mysqld/mysqld.sock for mounting volumes? – deosha Feb 10 '19 at 12:30
  • @deosha i'm connecting to the mysql container's bash. – jonarya Feb 10 '19 at 16:23

2 Answers2

3

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.

Shubhankar Naik
  • 374
  • 1
  • 3
  • 13
1

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 :)