Dockerホスト上のディレクトリを読み取り専用でコンテナに見せる方法
Dockerホスト上のディレクトリを読み取り専用でコンテナに見せるには--mountオプションのディレクトリ名の後に,readonlyを付与してdocker container runコマンド実行します。
オプションの説明(抜粋)
$ docker container run --help Usage: docker container run [OPTIONS] IMAGE [COMMAND] [ARG...] Run a command in a new container Options: -i, --interactive Keep STDIN open even if not attached --mount mount Attach a filesystem mount to the container --name string Assign a name to the container -t, --tty Allocate a pseudo-TTY
オプションの説明
- --mountオプション:ホストOSが提供するディレクトリをコンテナに見せる
- -iオプション:Dockerコンテナ起動時に、標準入力(STDIN)を受け付ける
- -tオプション:仮想端末(pseudo-TTY)をコンテナに割り当てる
- --nameオプション:作成するコンテナに名前を付ける
- ※-i -tを同時に使用する場合は、-itオプションを使用できます
,readonlyを指定した場合
$ mkdir $HOME/hostdir01 # コンテナに見せるディレクトリを作成
$ echo "Hello" > $HOME/hostdir01/testfile01.txt # ホストOS側にファイルを作成
$ docker container run -it --name test01 --mount type=bind,src=$HOME/hostdir01,dst=/root/ctdir01,readonly centos:7.7.1908 /bin/bash
[root@3e1a3519d843 /]# ls /root/ctdir01/
testfile01.txt
[root@3e1a3519d843 /]# cat /root/ctdir01/testfile01.txt
Hello
[root@3e1a3519d843 /]# rm -f /root/ctdir01/testfile01.txt
rm: cannot remove '/root/ctdir01/testfile01.txt': Read-only file system
[root@3e1a3519d843 /]# echo "Hello" >> /root/ctdir01/testfile01.txt
bash: /root/ctdir01/testfile01.txt: Read-only file system
[root@b65328f17905 /]# CTRL+P、CTRL+Qでコンテナから離脱
$ ls $HOME/hostdir01 # ファイルはそのまま
testfile01.txt
,readonlyを指定しない場合
$ docker container run -it --name test01 --mount type=bind,src=$HOME/hostdir01,dst=/root/ctdir01 centos:7.7.1908 /bin/bash
[root@b65328f17905 /]# ls /root/ctdir01/
testfile01.txt
[root@b65328f17905 /]# cat /root/ctdir01/testfile01.txt
Hello
[root@b65328f17905 /]# rm -f /root/ctdir01/testfile01.txt
[root@b65328f17905 /]# CTRL+P、CTRL+Qでコンテナから離脱
$ ls $HOME/hostdir01 # ファイルは削除されている