Search code examples
dockercontainersdocker-volume

Strange issue about applying docker named volume for new container


As I understand from all the information I found, the docker host volume can be created from three ways:

1- by ignoring the host-path (it will automatically create a directory with random ID)

2- by specify the host-path (it will also automatically create a directory with random ID)

3- by named volume and specify to a host-path

So I was trying first 2 ways:

$ docker run --name mongo-docker -v /data/db -p 27017:27017 -d mongo
$ docker run --name mongo-docker2 -v $(pwd)/data/:/data/db -p 27222:27017 -d mongo

And I look at the docker volume list:

$ docker volume ls

DRIVER    VOLUME NAME
local     5b829a731245cb7fe3a1f28aca4c4c3c3791105be228182ccb9b2f72319180c8
local     fb058e804412fb56b2096e2cb903e3ae73647ef6ca076ad9003708b80f94ffc5

It looks just what I was expected.

But when I tried the last one, by created first a volume:

$ docker volume create mongoVol
mongoVol

$ docker volume ls
DRIVER    VOLUME NAME
local     mongoVol

and use it for host-volume path, came up like this:

$ docker run --name mongo-docker3 -v mongoVol:/data/db -p 27322:27017 -d mongo
86bea0e52c9f395268665e191edc59f795d07266f17667502c7fa32879a6e021

$ docker volume ls
DRIVER    VOLUME NAME
local     0de25c92be504d0a6b9bb9c83aa8a6fe17bf9bc195562314ca49edb1c4cf4377   <=== create a new one for new container?
local     mongoVol

Why is this create a new directory for it? Shouldn't it be just the "mongoVol" volume?

I can’t find answers to related questions on any forum, post nor any videos....


Solution

  • The mongo image's Dockerfile has two directories named in a VOLUME statement. You're mounting content on /data/db but not on /data/configdb.

    If the Dockerfile declares a directory as a VOLUME and nothing is explicitly mounted there, Docker automatically creates an anonymous volume (your first case). That's what results in the additional volume appearing in the docker volume ls listing.