Cant connect to local mysql server through socket /var/run/mysqld/mysqld.sock (2)

Mysql 클라이언트 접속시 Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'  [우분투 리눅스] 문제 해결

우분투 Ubuntu 리눅스 환경에서 테스트용 가상머신에서 Mysql 이 잘 돌아갔는데,  다른 Ubuntu 환경에 들어가보니 MySQL 클라이언트 커맨드가 동작하지 않고

Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'   에러 메세지를 나옵니다

원인이라 한다면..

mysqld 가 사용하는 socket 파일이 다른 경로 (가령 저의 경우는 /tmp/mysql.sock 에 있더군요) 에 있는데,  PHP 나 MySQL 클라이언트 프로그램이 다른경로  에서 찾으려 하기 때문입니다.   그래서 mysqld 와 연결(connect)이 안되는 겁니다.

가장 간단히 해결하는 방법은

mysql 클라이언트 구동시 --socket=/tmp/mysql.sock 을 명시해주는 겁니다.

$mysql -u root -p --socket=/tmp/mysql.sock 이라고 실행하면

강제적으로 소켓파일을 원하는 디렉토리에서 만들도록 해줍니다.

참고로
PHP로 MySQL 연동시 위와 같은 Can't connect to local MySQL server through socket  에러가 발생하면

$conn = mysql_connect("localhost:/tmp/mysql.sock","db_user","db_passwd"); 

C API 로 MySQL 연동시 위와 같은 Can't connect to local MySQL server through socket  에러가  발생하면

mysql_real_connect(&conn, DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_PORT, "/tmp/mysql.sock", 0);

와 같이 소켓을 명시적으로 지정해주면 됩니다.

갑자기 잘되던 Mysql이 재부팅 후 먹통이 되는 난감한 상황이 발생하였다.

위와 같은 오류가 발생하며 mysql을 restart를 해도 실행되지 않는 오류가 발생하였다.

1. 가이드 대로 서버 복구 강제 실행하기

MySQL :: MySQL 5.7 Reference Manual :: 14.22.2 Forcing InnoDB Recovery

14.22.2 Forcing InnoDB Recovery To investigate database page corruption, you might dump your tables from the database with SELECT ... INTO OUTFILE. Usually, most of the data obtained in this way is intact. Serious corruption might cause SELECT * FROM tbl_

dev.mysql.com

2. 데이터베이스 데이터 폴더 접근권한 부여

3. mysql 재시작

다시 Mysql이 정상적으로 실행되었다.

//medium.com/@alef.duarte/cant-connect-to-local-mysql-server-through-socket-var-run-mysqld-mysqld-sock-155d580f3a06

위 링크에서 확인하면

sudo /etc/init.d/mysql start

를 실행하면 된다고 한다.

하지만 실행하면

-su: 19: /etc/profile.d/wsl-integration.sh: cannot create //.cache/wslu/integration: Directory nonexistent

이런 에러가 떠서
//github.com/wslutilities/wslu/issues/101 여기를 찾아보니

/etc/profile.d/wsl-integration.sh 파일을 에디터로 편집해야 한다고 한다.
내용은 링크에 나와있듯이, 파일의 최상단(WSL_INTEGRATION_CACHE=$HOME/.cache/wslu/integration 위)에

if [[ "${HOME}" == "/" ]]; then exit 0 fi

위와 같이 적어준다.

그리고 혹시 모르니 터미널을 한번 종료해주자.

그러면 sudo /etc/init.d/mysql start를 실행해도 문제가 없다.

그런데 mysql 재시작을 위해
sudo /etc/init.d/mysql restart 를 실행하면

/etc/profile.d/wsl-integration.sh: [[: not found 이런 에러가 떴는데, 찾아보니 bash가 아닌 shell을 사용하고 있을 때 문법이 달라 나타난다고 한다.(필자는 zsh 사용중)
그래서 위의 if [[ "${HOME}" == "/" ]]를
if [ "${HOME}" = "/" ] 처럼 수정하니 해결되었다.

마지막으로 발생한 에러는 No directory, logging in with HOME=/ 에러였는데,
이는 위의 깃허브 링크에서 가장 밑을 확인하면 해결방법이 나와있다.

sudo service mysql stop sudo usermod -d /var/lib/mysql/ mysql sudo service mysql start

위처럼 실행해주면 재시작도 잘 되는 것을 볼 수 있다.

[실행환경]
Windows 10
Ubuntu 18.04 LTS
mysql ver14.14 Distrib 5.7.31

ubuntu에서 mysql을 실행 시킬 때
/etc/init.d/mysql start 혹은 mysql -u root -p 등을 사용할 것이다.
만약 Windows에서도 mysql을 사용하고 있다면 이러한 에러를 발견할 수 있다.

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

저 에러는

 1. /var/run/mysqld/mysqld.sock 소켓파일이 없거나(찾을 수 없거나)

 2. port number가 같은 경우 충돌이 일어날 때 발생 할 수 있다.

$ cat /var/log/mysql/error.log

위 명령어로 mysql error log를 본 후 어떤 문제인지 판별 할 수 있다.

1의 경우에는 내가 겪은 경우가 아니라 자세히 알진 못하지만 재설치를 하면 해결된다는 것 같다.

2의 경우가 내가 겪은 상황인데 로그파일에 아래 에러 로그가 적혀있었다.

[ERROR] Do you already have another mysqld server running on port: 3306 ?

이미 3306 port number를 사용하고 있다는 말이다. port number를 바꿔주면 된다.윈도우에서 우분투를 사용할 때 mysql 설정파일 경로는 /etc/mysql/mysql.conf.d/mysqld.cnf 이며,
[mysqld] 아래에 있는 port 부분을 안쓰는 포트넘버로 바꿔주면 된다.

$ /etc/init.d/mysql restart

위의 명령어로 mysql을 재시작하고 다시 실행시키면 제대로 동작하는 것을 볼 수있다.

PS

위의 방법은 나에게 임시적인 방편(?)인 것 같다. 당장 에러가 날 때 포트넘버를 바꾸면 제대로 동작하지만 어찌된 일인지 며칠이 지나면 다시 포트넘버 충돌이 일어나서 포트넘버를 다른 넘버로 바꿔야한다. 여기에 대한 내용은 찾을 수 없어서 귀찮지만... 어쩔 수 없이 이렇게 쓰고 있다...

Introduction

Users working with MySQL can run into the error 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock (2)' when logging into the MySQL interface. This problem usually arises if MySQL can't access the mysqld.sock socket file.

In this tutorial, we will go over the potential causes of the 'Can't connect to local MySQL server through socket' error and show you different methods of resolving this issue.

Prerequisites

  • A system running Ubuntu 20.04
  • A user account with sudo privileges
  • Access to the terminal window/command line
  • A copy of MySQL installed and ready to use (learn how to install it with our guide to installing MySQL on Ubuntu 20.04)

Resolving the 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' Error

There are multiple ways to solve the 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock (2)' error. If one solution doesn't work, move down the list until you find the one that resolves the issue.

Method 1: Check the MySQL Service

1. Check the status of the MySQL service with:

sudo systemctl status mysql

2. If the service is not running, restart it by using:

sudo systemctl start mysql

3. To prevent this issue from happening, set the MySQL service to automatically start at boot:

sudo systemctl enable mysql

Method 2: Verify the mysqld.sock Location

The 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' error also happens if MySQL can't find the mysql.sock socket file.

1. Find the current mysqld.sock location by using the find command to list all the socket files on your system:

sudo find / -type s

2. Open the MySQL configuration file in a text editor of your choice. In this example, we use nano:

sudo nano /etc/mysql/my.cnf

3. Then, add the following lines at the end of the MySQL configuration file:

[mysqld] socket=[path to mysqld.sock] [client] socket=[path to mysqld.sock]

Where:

  • [path to mysqld.sock]: Path to the mysqld.sock socket file you found in Step 1.

Another method is to create a symlink from the location of mysqld.sock to the /var/run/mysqld directory:

ln -s [path to mysqld.sock] /var/run/mysqld/mysqld.sock

4. Press Ctrl+X to close the configuration file and type Y and press Enter to save the changes you made.

4. Finally, restart the MySQL service:

sudo systemctl restart mysql

Method 3: Check the MySQL Folder Permission

Another potential cause could be that the MySQL Service can't access the /var/run/mysqld directory due to permission restrictions:

1. To resolve this issue, change the permission settings for the mysqld directory with:

sudo chmod -R 755 /var/run/mysqld

Setting the permission to 755 allows the root user to read, write, and execute the directory, while other users can only read and execute.

2. Restart the MySQL service for the changes to take effect:

sudo systemctl restart mysql

Method 4: Check for Multiple MySQL Instances

The error also occurs if there are multiple instances of MySQL running at the same time.

1. To list all the instances of MySQL, use:

ps -A|grep mysqld

2. If there are multiple MySQL instances running, terminate them with:

sudo pkill mysqld

3. Restart the MySQL service to start a single instance of MySQL:

sudo systemctl restart mysql

Conclusion

After reading this tutorial, you should have identified the cause of the 'Can't connect to local MySQL server through socket' error and applied the appropriate solution.

For more help with using MySQL, consult our MySQL Commands Cheat Sheet.

Toplist

Neuester Beitrag

Stichworte