LoginSignup
52
45

More than 5 years have passed since last update.

docker-composeでMySQLに接続する

Last updated at Posted at 2017-02-12

MySQLを利用したdocker-composeを書く

以下のような感じで書く。

docker-compose.yml
dbserver:
    build: ./mysql
    ports:
     - 3306:3306
    hostname: dbserver
    environment:
        MYSQL_DATABASE: order
        MYSQL_ROOT_PASSWORD: password
app:
    build: ./
    ports:
     - 8080:8080
    links:
     - dbserver
    volumes:
     - $PWD:/usr/src/app
    tty: true

docker-compose up -d をする

$ docker-compose up -d
Recreating talk_dbserver_1
Recreating talk_app_1

$ docker-compose ps
     Name                   Command             State           Ports          
------------------------------------------------------------------------------
talk_app_1        python3                       Up      0.0.0.0:8080->8080/tcp 
talk_dbserver_1   docker-entrypoint.sh mysqld   Up      0.0.0.0:3306->3306/tcp 

appに入ってMySQLに接続する

下の感じ。

$ docker exec -it talk_app_1 bash
python@9726b9fddf22:/mysql-connector-python$ mysql -h dbserver -P 3306 -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.17 MySQL Community Server (GPL)

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

ちなみに

$ docker exec -it talk_dbserver_1 bash
root@dbserver:/# env
HOSTNAME=dbserver
TERM=xterm
MYSQL_VERSION=5.7.17-1debian8
MYSQL_DATABASE=order
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
PWD=/
SHLVL=1
HOME=/root
MYSQL_MAJOR=5.7
no_proxy=*.local, 169.254/16
affinity:container==aa15c60aa635af3cc91bcc6092b9d20f32dc3bc1d9b4557e8469c567c8c88173
GOSU_VERSION=1.7
MYSQL_ROOT_PASSWORD=password
_=/usr/bin/env
root@dbserver:/# hostname -i
172.17.0.2

ip直指定でも入れる。

$ docker exec -it talk_app_1 bash
python@9726b9fddf22:/mysql-connector-python$ mysql -h 172.17.0.2 -P 3306 -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 5
Server version: 5.7.17 MySQL Community Server (GPL)

Copyright (c) 2000, 2016, 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> 
52
45
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
52
45