2
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?

More than 5 years have passed since last update.

docker -v オプションではホスト側のフォルダが存在していなくてもエラーは出ない

Posted at

久々にdockerをいろいろ使ってみていたので(再入門レベル)ちょっと気になったことを書いてみる。

結論

-vオプションではなく、--mountオプションを使いましょう。

経緯

dockerを使っていると、-vオプションでたまにフォルダ名をタイポしたりしていて、思ったとおりマウントできていなかった。
(あとWindowsの方使ってるとパスの表記でハマったりする。ドキュメントしっかり読めばいいだけなんですけどね)

docker run -it -v $(pwd)/somedisk:/hoge alpine sh
→ホスト側にsomediskというフォルダがなくても、コンテナ側にhogeというフォルダは作られる。(中身は空)

$ docker run -it -v $(pwd)/somedisk:/hoge alpine sh
/ # ls
bin    dev    etc    hoge   home   lib    media  mnt
opt    proc   root   run    sbin   srv    sys    tmp    usr    var

docker run -it --mount type=bind,src=$(pwd)/somedisk,dst=/hoge alpine sh
→ホスト側にsomediskがないとエラー

$ docker run -it --mount type=bind,src=$(pwd)/somedisk,dst=/hoge alpine sh
docker: Error response from daemon: invalid mount config for type "bind": bind source path does not exist: /home/user/docker/somedisk.
See 'docker run --help'.

調べた

https://github.com/moby/moby/pull/21666
https://github.com/moby/moby/issues/13121
以前は-vで存在しないホスト側ディレクトリを指定すると勝手に作成していたみたい。
で、勝手に作成されないようになったんだけど、エラーは出たりしない、ということかな。

なので-v--mount type=bind,...に変えて使いましょう。

Windows Docker Desktopでは

WSLからdocker.exeを使う場合

$ docker.exe run -it --mount type=bind,src=$(pwd)/hoge,dst=/hoge alpine
C:\Program Files\Docker\Docker\resources\bin\docker.exe: Error response from daemon: invalid mount config for type "bind": bind source path does not exist:

windows形式のパスを指定しないとエラーになる。(wslのaptとかで入れるとエラーにならないのかも)
docker.exe run -it --mount type=bind,src=$(wslpath -w $(pwd)/hoge),dst=/hoge alpine
こんな風にwindowsのパスに変換しましょう。

ただし、記事時点のDocker Windowsではホストパスが存在しない場合は--mountオプションでもホスト側にフォルダが勝手に作成される。
エラーも出ません。気をつけましょう。

2
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
2
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?