背景
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>