Help us understand the problem. What is going on with this article?

DockerのMySQLコンテナに外部のサーバーから接続する

概要

DockerでMySQLコンテナを立て、ホストOS、または外部サーバーから接続する方法。

docker runの場合

$ sudo docker run \
    --rm \
    -v $(pwd)/db/mysql_init:/docker-entrypoint-initdb.d \
    -v $(pwd)/db/mysql_data:/var/lib/mysql \
    --name mysql \
    -e MYSQL_ROOT_PASSWORD=your_password \
    --hostname my-mysql \
    -e BIND-ADDRESS=0.0.0.0 \
    -p 3306:3306 \
    -itd mysql:5.7

docker-composeを使う場合

docker-compose.yml
version: '3.1'

services:
  db:
    image: mysql:5.7
    restart: always
    hostname: my-mysql
    env_file:
      - .env
    environment:
      MYSQL_USER: sample_user
      MYSQL_DATABASE: sample_db
      TZ: "Asia/Tokyo"
      BIND-ADDRESS: 0.0.0.0
    ports:
      - 3306:3306
    # データを永続化させる場合
    volumes:
      # 初期データを投入するSQLが格納されているdir
      - ./db/mysql_init:/docker-entrypoint-initdb.d
      # 永続化するときにマウントするdir
      - ./db/mysql_data:/var/lib/mysql
    tty: true

envファイルにMySQLのROOTのパスワードを定義する

.env
MYSQL_ROOT_PASSWORD=your_password

コンテナ起動

$ docker-compose up -d --build

MySQLに接続

ホストOSから接続

$ mysql -u root -p -h localhost -P 3306 --protocol=tcp

外部のサーバーから接続

$ mysql -u root -p -h hostname -P 3306 --protocol=tcp
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした