0
0

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】Bindマウントとは

Last updated at Posted at 2025-10-14

概要

  • Bindマウントはホストとコンテナでディレクトリを直接共有する手段
    → コンテナ内の変更がリアルタイムでホストに反映されるため、データの永続化や開発効率向上に便利
  • readonly オプションを使うとコンテナからの書き込みを防止できる
    → 誤ってホストデータを書き換えるリスクを防ぐ
  • コンテナを削除してもホストのデータは残る
    → データの永続性を確保できる
  • コンテナ内で操作したファイルはホスト側にも反映される
    → 開発やテストでコンテナを自由に作り直してもデータを保持できる

1. Bindマウントの基本例

(1) ホストディレクトリを用意する

mkdir /bindhost
echo "hello bind" > /bindhost/hello.txt
  • Bindマウントでは「ホスト側に存在するディレクトリ」を指定する必要がある
  • hello.txt を作成することで、マウント後にコンテナ側から確認できるサンプルファイルを用意

(2) AlpineコンテナでBindマウントを指定して起動

docker container run --rm -d \
  --name bct \
  --mount type=bind,source=/bindhost,target=/bindcont \
  alpine:3.10.3 tail -f /dev/null

オプション解説

  • --rm:コンテナ終了時に自動で削除
    → 開発中に不要なコンテナを残さないようにするため

  • -d:デーモンモードで起動
    → コンテナをバックグラウンドで動作させつつ、他の操作をターミナルで続けられる

  • --mount type=bind,source=<ホスト>,target=<コンテナ>:ホストディレクトリをコンテナ内にマウント
    → ホストとコンテナで同じディレクトリを共有するための必須設定

  • tail -f /dev/null
    →Alpineはコンテナを起動してもプロセスがすぐ終了するため、tail -f /dev/null で無限ループ的に待機させ、コンテナを停止させないようにする


(3) コンテナ内からホストのファイルを確認

docker container exec bct ls /bindcont
# 出力: hello.txt
  • Bindマウントが正しく反映されているか確認する
  • /bindcont はコンテナ内でのマウント先ディレクトリ

(4) コンテナ内で新しいファイルを作成

docker container exec bct touch /bindcont/hello2.txt
  • コンテナ内でファイル作成がホスト側に反映されるか確認
  • データ共有が正しく機能しているかの検証

(5) ホスト側でファイルを確認

ls /bindhost
# 出力: hello.txt  hello2.txt
  • Bindマウントでコンテナ内の操作がホストに反映されることを確認
  • ホストとコンテナでデータの同期ができる

2. NginxコンテナでBindマウント(読み取り専用)

docker container run --rm -d \
  --name nginx \
  -p 8080:80 \
  --mount type=bind,source=/bindhost,target=/usr/share/nginx/html,readonly \
  nginx:1.17.6-alpine
  • readonly オプションを付けることでコンテナからホストへの書き込みを禁止
  • Nginxのように静的コンテンツを参照するだけのコンテナに適している
  • 誤操作でホスト側データを書き換えられるリスクを防止

(1) 読み取り専用の確認

docker container exec nginx touch /usr/share/nginx/html/hello3.txt
# エラー: Read-only file system
  • readonly が正しく効いているか検証
  • 読み取り専用の場合、コンテナからホストファイルを作成・変更できない
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?