はじめに
Docker環境で、MySQLをよく構築するが何も考えずに
いつもコピペしたいたので、改めて公式ドキュメントを読みつつ理解していく。
まあ、構築自体は色々記事はあるけどだいたい公式ドキュメントのソースがないから
本当にあっているかの検証。
今回のリポジトリは以下にあります
構築
今回は、Dockerのコンテナを作り変えてもデータは残るように
データ用のディレクトリをマウントして運用するようにする
dataディレクトリは上記リポジトリには無いが、ビルド時に生成されるので追加しなくてもOK
.
|_.env
|_.docker-compose.yml
|_data
|_db_store *ここに実際のDB情報が入る
Docker
ここからは実際のdocker-composeを見ていく
実装
version: "3.8"
services:
db:
image: mysql:8.4
container_name: db_sample
environment:
MYSQL_ROOT_PASSWORD: ${ROOT_PASS}
MYSQL_DATABASE: ${DB_NAME}
MYSQL_USER: ${DB_USER}
MYSQL_PASSWORD: ${DB_PASS}
TZ: ${TZ}
ports:
- ${DB_PORT}:3306
volumes:
- ./data/db-store:/var/lib/mysql
image
今回は2024年4月にアップデートされた、8.4を使う現状のLTS版なので
特段理由がないなら、このバージョンを使っていけばよいのではないだろうか
ちなみに mysql:8.4 と指定しているが、公式では以下のサポートがされている
8.4.3, 8.4, 8, lts, 8.4.3-oraclelinux9, 8.4-oraclelinux9, 8-oraclelinux9, lts-oraclelinux9, 8.4.3-oracle, 8.4-oracle, 8-oracle, lts-oraclehttps://hub.docker.com/_/mysql
container_name
ここは特筆することはないが、コンテナの名前なのでお気に召すままに入れればよいのではないだろうか。
environment
ここで、DBの環境を構築している
値は.envファイルから持ってくるようになっている。
ROOT_PASS=root
DB_NAME=sample-db
DB_USER=user
DB_PASS=p@ssw0rd
DB_PORT=3306
TZ=Asia/Tokyo
MYSQL_ROOT_PASSWORD
MYSQL_ROOT_PASSWORD は必須らしい。
ルート、スーパユーザに設定されるパスワードとのこと。
接続するときとかに使う情報である。
This variable is mandatory and specifies the password that will be set for the MySQL root superuser account. In the above example, it was set to my-secret-pw.https://hub.docker.com/_/mysql
MYSQL_DATABASE
任意のオプションらしい。
作成するDBの名前をつけるオプション。
ちなみに、このオプションを付けないとDBが作成されないので、
自分で作る必要がある
ユーザとパスワードが設定された場合スーパーユーザの権限が付与されるらしい。
This variable is optional and allows you to specify the name of a database to be created on image startup. If a user/password was supplied (see below) then that user will be granted superuser access (corresponding to GRANT ALL ) to this database.
MYSQL_USER
上記で書いたスーパーユーザ権限のあるアカウントを作る
These variables are optional, used in conjunction to create a new user and to set that user’s password. This user will be granted superuser permissions (see above) for the database specified by the MYSQL_DATABASE variable. Both variables are required for a user to be created.
Do note that there is no need to use this mechanism to create the root superuser, that user gets created by default with the password specified by the MYSQL_ROOT_PASSWORD variable.https://hub.docker.com/_/mysql
MYSQL_PASSWORD
上記同様のパスワード版
rootユーザには必要ないらしい。rootは前述の
MYSQL_ROOT_PASSWORD が適用されるとのこと(上記参考文献を参照のこと)
TZ
みんな使っているけど、ドキュメントから探せなかった….
やっている事自体はDBのタイムゾーンの設定だけど…
今回は日本なのでAsia/Tokyo にしている。
さいごに
公式ドキュメントを見て、スーパーユーザの権限が付与されているということを知った。
やっぱり公式ドキュメントは見ようね!
以下の記事と組み合わせればフルスタックな環境はすぐできそう

コメント