19
15

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 1 year has passed since last update.

Docker Compose データベースのバックアップとリストア方法

Last updated at Posted at 2022-06-20

構成例

docker-compose.yml
version: "3.9"
volumes:
  db-store:
services:
  db:
    image: mysql/mysql-server:8.0
    volumes:
      - type: volume
        source: db-store
        target: /var/lib/mysql
        volume:
          nocopy: true
    environment:
      - MYSQL_DATABASE=${DB_DATABASE:-laravel}
      - MYSQL_USER=${DB_USERNAME:-phper}
      - MYSQL_PASSWORD=${DB_PASSWORD:-secret}
      - MYSQL_ROOT_PASSWORD=${DB_PASSWORD:-secret}

こんな感じのMySQLのデータベースコンテナを用意しました。
こちらのバックアップとリストアの手順をご紹介します。

ログイン確認

$ docker compose exec db bash -c 'mysql -u $MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DATABASE'

コンテナ内の環境変数を使いたいので bash -c でコンテナ内で実行して欲しいコマンドを渡してます。
MySQLへログインできればOKです。

バックアップ

$ docker compose exec db bash -c 'mysqldump --no-tablespaces -u $MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DATABASE > /tmp/dump.sql'
$ docker compose cp db:/tmp/dump.sql /tmp/dump.sql

シンプルに mysqldump コマンドを実行して dump ファイルを出力してます。
docker compose cp コマンドでコンテナ内のファイルをローカルへコピーします。

リストア

$ docker compose cp /tmp/dump.sql db:/tmp/dump.sql
$ docker compose exec db bash -c 'mysql -u $MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DATABASE < /tmp/dump.sql'

# 不要であればローカルのdumpファイルを削除
$ rm /tmp/dump.sql

docker compose cp コマンドはローカルからコンテナ内へコピーもできます。
コピーしたdumpファイルを mysql コマンドでインポートします。

補足

mysqldump --no-tablespaces オプション

--no-tablespaces オプションを付けないと下記のエラーが発生します。

mysqldump: Error: 'Access denied; you need (at least one of) the PROCESS privilege(s) for this operation' when trying to dump tablespaces

19
15
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
19
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?