[小ネタ]Docker コンテナをボリュームごと削除する

2023.03.23

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

Docker で立ち上げたDBコンテナにマイグレーションコマンドを投げたところ失敗してしまい、コンテナがクラッシュするようになってしまいました。

docker compose up -d

npx prisma migrate dev

Environment variables loaded from .env
Prisma schema loaded from schema.prisma
Datasource "db": MySQL database "sampledb" at "127.0.0.1:3306"

- The migration `2023010100000_` failed.
- Drift detected: Your database schema is not in sync with your migration history.

The following is a summary of the differences between the expected database schema given your migrations files, and the actual schema of the database.

It should be understood as the set of changes to get from the expected schema to the actual schema.

[*] Changed the `sample` table
  [+] Added column `id_sample`


✔ We need to reset the MySQL database "sampledb" at "127.0.0.1:3306".
Do you want to continue? All data will be lost. … yes

Error: P3016

The fallback method for database resets failed, meaning Migrate could not clean up the database entirely. Original error: Error code: P1017

Server has closed the connection.

きっとマイグレーションがうまくいかなかったんだな、一度 DB をドロップしよう、と MySQLセッションをもう一度立ち上げてクエリを投げようと考えましたが、セッションに入ろうとするとコンテナが落ちてしまいます。

mysql -u root -p -h 127.0.0.1 -P 3306 --local_infile=1 -D sampledb

// ... Logs Omitted

mydb-data | Status: NOT_KILLED

mydb-data |

mydb-data | The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains

mydb-data | information that should help you find out what is causing the crash.

mydb-data exited with code 2

解決:Docker Compose で作ったコンテナ、イメージ、ボリューム、ネットワークを削除する

docker-compose rmdocker rmi、でコンテナとイメージを消してやり直してみましたが、このやり方だと volume は既存のものが利用されてしまいます。今回はマイグレーションに失敗したボリュームのせいでコンテナがクラッシュしていたため以下のコマンドでボリュームも含めてdocker compose関連全てのリソースを削除することで解決しました。

$ docker compose down --rmi all --volumes --remove-orphans

参考:《滅びの呪文》Docker Compose で作ったコンテナ、イメージ、ボリューム、ネットワークを一括完全消去する便利コマンド