4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

make コマンドから docker コンテナ上の MySQL にログインする

Posted at

背景

makeコマンドからdockerコンテナ上のMySQLに接続したかったのですが、固定文字列ではなくサーバー環境変数を使いたかったのでやり方を調べてみました。

環境

  • MySQL 8.0.17

docker-compose.yml

dbコンテナを用意します。

docker-compose.yml
version: "3"
services:
  db:
    image: mysql:8.0
    environment:
      - MYSQL_DATABASE=homestead
      - MYSQL_USER=homestead
      - MYSQL_PASSWORD=secret
      - MYSQL_ROOT_PASSWORD=secret
      - TZ=Asia/Tokyo

dbコンテナをビルドして起動します。

$ docker-compose up -d --build

Makefile

Makefile
mysql:
	docker-compose exec db bash -c 'mysql -u $$MYSQL_USER -p$$MYSQL_PASSWORD $$MYSQL_DATABASE'
  • bash の -c オプションで文字列としてコンテナに渡してコマンドを実行できます。
  • $$ 続けるとエスケープされてサーバー環境変数を文字列として渡せる。
$ make mysql
docker-compose exec db bash -c 'mysql -u $MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DATABASE'
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.17 MySQL Community Server - GPL

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

参考

4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?