LoginSignup
22
13

More than 3 years have passed since last update.

dockerからmysqlに接続できない【ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)】

Posted at

dockerを利用していて、mysqlに接続したかったのですが、下記のエラーに悩まされていました。

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

試したこと

※以下に記載している#で始まるコマンドは全てコンテナ内で実行しているものです。いかにdocker-compose.ymlを記載しておきます。

docker-compose.yml
version: '3'
services:
  node:
    build:
      context: .
      dockerfile: Dockerfile
    volumes:
      - ./:/usr/src/app
    command: sh -c "npm run dev"
    ports:
      - '3000:3000'
  db:
    image: mysql:latest
    restart: always
    hostname: my-mysql
    env_file:
      - .env
    environment:
      MYSQL_USER: sample_user
      MYSQL_PASSWORD: password
      MYSQL_DATABASE: sample_db
      MYSQL_ROOT_PASSWORD: password
    ports:
      - 3306:3306
    expose:
      - '3306'
    volumes:
      - ./db/mysql_init:/docker-entrypoint-initdb.d
      - ./db/mysql_data:/var/lib/mysql
    tty: true

上記のymlファイルをもとにimageをビルドし、コンテナを起動してコンテナに入ります。


$ docker-compose build

$ docker-compose up -d

$ docker-compose exec db sh

さて、上記のエラーメッセージで検索するとこちらの記事が出てきたので、ここで記載されている内容を参考に試してみました。

STEP1 touch /tmp/mysql.sock

エラーメッセージをみる限り、mysqld.sockが無いために接続できていないのでは(?)と思い、以下のコマンドを実行してファイルを作成しました。

# touch /tmp/mysql.sock

STEP2 ファイルの作成後、mysqlを再起動

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

同じエラーが。。。

そこで、一旦dockerとmysqlについて調べていると以下の記事を発見しました。
docker-composeでMySQLに接続する

成功した方法

記事を参考に、試します。

STEP1 envコマンドでipアドレスを調べる

どうやらipアドレスを指定することでmysqlに接続できそうだということがわかったので、下記コマンドを実行

# env
DATABASE_URL=mysql://root:password@localhost:3306/mydb
HOSTNAME=my-mysql
MYSQL_MAJOR=8.0
HOME=/root
MYSQL_ROOT_PASSWORD=password
TERM=xterm
MYSQL_PASSWORD=password
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
MYSQL_VERSION=8.0.19-1debian10
MYSQL_USER=sample_user
GOSU_VERSION=1.7
PWD=/
MYSQL_DATABASE=sample_db

下記コマンドでipアドレスを表示します。

# hostname -i
172.27.0.3

STEP2 mysqlに接続

# mysql -h 172.27.0.3 -P 3306 -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 8.0.19 MySQL Community Server - GPL

Copyright (c) 2000, 2020, 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>

できた!!!✨

22
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
13