Error 2002 (hy000): cant connect to local mysql server through socket /tmp/mysql.sock (2) docker

Tools/docker

[docker] Docker로 MySQL 컨테이너 실행시 로그인 안됨 해결방법

MOMOBOB 2021. 11. 5. 21:52

docker run --name <container name> -e MYSQL_ROOT_PASSWORD=<your password> -d mysql:8 docker exec -it <container name> mysql -p

MySQL의 공식 이미지를 이용하여 컨테이너를 실행하고 컨테이너의 mysql 접속시 아래와 같은 에러와 함께 로그인 안되는 문제가 발생함.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

MySQL의 컨테이너가 올라가면서 MySQL 데몬이 가동되고 있지 않아서 나는 에러였고, 도커 명령어로 컨테이너 재기동하면 정상동작 함.

docker stop <container name> docker start <container name> // 혹은 docker restart <container name>
Error 2002 (hy000): cant connect to local mysql server through socket /tmp/mysql.sock (2) docker

** ps : 이상하게 컨테이너 생성시 특수문자(^) 입력하면 로그인 계속 실패함... 이것 때매 뚜껑열릴뻔... 휴

[db] mac에서 mysql환경설정 셋팅하기 1편 - 설치 및 접속, ERROR 2002 (HY000) : Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2) 해결방법

mac에서 mysql을 환경설정하는 방법에 대해서 다뤄보도록 하겠습니다.

그동안 aws에서 제공하는 rds를 사용했기 때문에 로컬 디비를 거의 안썼는데
테스트 하고 싶은것이 있어 로컬에 디비설치를 하려고 했더니 몇몇 문제가 발생하여 공유하기 위해 정리를 해봅니다.

크게 설치 및 접속, 보안 및 chatset에 대해서 알아보겠습니다.

우선 아래의 설명은 homebrew가 설치가 되어있어 brew를 사용할 수 있다는 가정하에 설명을 진행을 하도록 하겠습니다.

$ brew install mysql

brew를 이용하여 mysql을 설치를 해줍니다.

리눅스 같은 경우는 mysql-server를 설치를 하는데 mac에서는 mysql을 설치를 하네요

$ mysql -u root -p Enter password: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

접속을 시도해 보았더니 로컬 서버에 접속을 할 수 없다고 뜹니다.

에러발생 원인: 디비서버 열려있지 않음.

해결방법: 디비서버 실행

디비를 설치를 했지만 실행을 하지 않았기 때문에 위와같은 에러가 발생을 하게 됩니다.
만약 linux사용자라면 service를 이용하여 서버를 실행시키겠지만
맥에서는 service를 지원을 하지 않는것 같아 다른 방법으로 시도를 해보았습니다.

$ mysql.server start Starting MySQL . SUCCESS!

mysql.server 명령어를 실행을 시켜주게 되면
/usr/local/bin/mysql.server
가 실행이 됩니다.

Docker 설정

설치방법

  1. 리포지토리(Repository): https://hub.docker.com/_/mysql/
  2. 사실 설치방법은 위의 리포지토리에 잘 적혀지 않습니다. 버전은 latest가 아닌 5.6을 기준으로 합니다.
  3. 이미지 가져오기

    $ docker pull mysql:5.6

    5.6: Pulling from library/mysql

    f17d81b4b692: Already exists

    c691115e6ae9: Pull complete

    41544cb19235: Pull complete

    254d04f5f66d: Pull complete

    4fe240edfdc9: Pull complete

    b79c3b745cc6: Pull complete

    c6ebcbee59b1: Pull complete

    e9bb65297d95: Pull complete

    2a7c8492496e: Pull complete

    6af69434adbe: Pull complete

    54bc8b20381b: Pull complete

    Digest: sha256:b56c3109f09a90c045ebe991e085fcaab5008cd6dbb8ab5ad1d6101fc0f87fcf

    Status: Downloaded newer image for mysql:5.6

  4. 데몬으로 실행하기

    $ docker run -d --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=my-secret-pw mysql:5.6

    21b4fc8a0a44ed4dc687ccce4a07c581840e29766fbd883c164cc9fcc51f0735

    $ docker ps

    CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES

    21b4fc8a0a44        mysql:5.6           "docker-entrypoint.s…"   3 seconds ago       Up 2 seconds        0.0.0.0:3306->3306/tcp   my-local-mysql

  5. id: root / pw: my-secret-pw

mysql CLI 설치 with brew in macOS X

$ brew install mysql

Updating Homebrew...

==> Auto-updated Homebrew!

Updated 2 taps (homebrew/core and homebrew/cask).

==> Updated Formulae

ace                    beagle                 gmsh                   pulumi                 tomcat

armor                  crc32c                 logstash               sourcekitten           xtensor

==> Downloading https://homebrew.bintray.com/bottles/mysql-8.0.12.high_sierra.bottle.tar.gz

######################################################################## 100.0%

==> Pouring mysql-8.0.12.high_sierra.bottle.tar.gz

==> /usr/local/Cellar/mysql/8.0.12/bin/mysqld --initialize-insecure --user=namo --basedir=/usr/local/Cellar/mysql/8.

==> Caveats

We've installed your MySQL database without a root password. To secure it run:

    mysql_secure_installation

MySQL is configured to only allow connections from localhost by default

To connect run:

    mysql -uroot

To have launchd start mysql now and restart at login:

  brew services start mysql

Or, if you don't want/need a background service you can just run:

  mysql.server start

==> Summary

🍺  /usr/local/Cellar/mysql/8.0.12: 255 files, 233.0MB

$ mysql

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

음, 접속을 할 수 없다고 나온다. 검색.. Linux DB

이 에러의 원인은 MYSQL의 소켓 파일인 mysql.sock 파일이 없거나 정확하지 않아서 발생하는 에러입니다. MYSQL이 실행되면 MYSQL 소켓 파일이 /tmp/ 디렉토리에 다음과 같이 생성되게 되는데 해당 에러는 mysql.sock 파일의 위치가 다른 경우입니다. 이 경우 다음과 같이 조치합니다.

아마도 docker내에 mysql.sock 파일이 생성되었을 테니, 시스템 상에서는 해당 파일이 보이지 않을 것이다.

docker에서 띄어져 있는 mysql에 CLI 접속

우선 docker에서 LISTEN하고 있을 포트를 시스템으로 포워딩을 해주어야 한다.

docker ps 명령으로 확인이 가능하다. 아래 끝쪽에 보면 도커 내의 3306 포트가 시스템의 3306으로 매핑이 되어 있다.

$ docker ps

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES

2fe68cbd6713        mysql:5.6           "docker-entrypoint.s…"   20 hours ago        Up 20 hours         0.0.0.0:3306->3306/tcp   mysql

이젠 host와 port를 지정해주면 socket이 아닌 TCP로 연결이 된다. --user

- h : host
- P : port
--user : 사용자명
--password : 이것은 패스워드를 프롬프트 상에서 입력 받겠다는 인자
mydb : 접속할 DB명

$ mysql -h 127.0.0.1 -P 3306 --user=root --password mydb

Enter password:

Reading table information for completion of table and column names

You can turn off this feature to get a quicker startup with -A

Welcome to the MySQL monitor.  Commands end with ; or \g.

Your MySQL connection id is 260

Server version: 5.6.42 MySQL Community Server (GPL)

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> exit

Bye

접속 성공!

시스템 timezone 확인 하기

mysql> SELECT @@global.time_zone, @@session.time_zone;

+--------------------+---------------------+

| @@global.time_zone | @@session.time_zone |

+--------------------+---------------------+

| SYSTEM             | SYSTEM              |

+--------------------+---------------------+

1 row in set (0.00 sec)

SYSTEM은 시간대 설정이 현재 시스템의 타임 존과 동일하다는 말이다.
global과 session 두 가지가 있는데, 글로벌은 DB전체에 영향을 미치는 것이고 session은 접속한 커넥션에 적용되는 타임존이다.

만약 서울 시간대로 설정하고 싶으면 'Asia/Seoul'를 사용하면 된다. (아래는 글로벌 설정)

mysql> SET GLOBAL time_zone = 'Asia/Seoul';

Query OK, 0 rows affected (0.00 sec)

mysql> SELECT @@global.time_zone, @@session.time_zone;

+--------------------+---------------------+

| @@global.time_zone | @@session.time_zone |

+--------------------+---------------------+

| Asia/Seoul         | SYSTEM              |

+--------------------+---------------------+

1 row in set (0.00 sec)

mysql> exit

Bye

만약 현재 접속한 세센의 타임존만 마꾸고 싶으면 GLOBAL을 빼고 수행한다.

mysql> SET time_zone = 'Asia/Seoul';

Query OK, 0 rows affected (0.00 sec)

mysql> SELECT @@global.time_zone, @@session.time_zone;

+--------------------+---------------------+

| @@global.time_zone | @@session.time_zone |

+--------------------+---------------------+

| Asia/Seoul         | Asia/Seoul          |

+--------------------+---------------------+

1 row in set (0.00 sec)

세션 타임존을 변경하지 않고 재 접속을 하면 global 설정을 따라간다.