1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Docker】ボリューム vs バインドマウント ⚔️

Last updated at Posted at 2025-05-02

はじめに

コンテナを削除すると、基本的にはコンテナ内のデータも削除されます。
データを残したい場合は、以下のいずれかの方法を選択します。

  • ボリューム
  • バインドマウント

compose.yaml の書き方がごっちゃになりがちなのでメモ ✍️

ボリューム

Docker が管理する記憶領域にデータを永続化する仕組み

  • バインドマウントよりデータの移行やバックアップが容易
  • データを変更する際は、データを直接操作するのではなく、コンテナを通して行う
  • 直接変更することがないデータに向いている
    • ex. データベースのデータ

compose.yaml の書き方

compose.yaml
services:
  <container_name>:
    image: <image_name>
    volumes:
      - <volume_name>:path/to/container_dir

volumes: <volume_name>

バインドマウント

ホスト OS のディレクトリやファイルをマウントする仕組み

  • データを変更する際は、ホスト OS のファイルを直接変更する
    • コンテナ内にも自動で反映される
  • 変更の頻度が高いデータに向いている
    • ex. 開発中のプログラムのソースファイル

compose.yaml の書き方

compose.yaml
services:
  <container_name>:
    image: <image_name>
    volumes:
      - path/to/host_dir:path/to/container_dir

「仮想環境だから」と無邪気にバルス rm -rf / するとマウントしているホストのファイルも吹き飛びます。

結局どっち使えばいいの?

迷ったら ボリューム

公式でもボリュームの使用が推奨されています。

データを直接変更するする必要がある場合のみ、バインドマウントを選択するのがよいです。

おわりに

用途に応じて使い分けが大事。
どっちがどっちか分からなくなったら、ここを見にくる。

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?