I’ve read this post and this one. And the best explanation I’ve found is:
… outside you declare the volume and inside you specify how to mount it into a container. A volume has an independent life cycle from services. It can be mounted by several services and it will retain data if services are restarted.
I still do not understand why I need to specify volumes twice, even if a volume can be mounted several times in different services. I think I just understood this topic very bad.
2
Answers
So let‘s say you have two containers of the same image and you want to reference the volume again in the second container without having to specify where the resource is locally, but mount it at a different path in the second container, that‘s when you might use this. Otherwise only specifying it once per container is enough.
It may help to make a programming analogy.
A volume could be thought of like a function or method. You define a function only one time, but you can use that same function many times; no matter how many times or in how many places you use the function, it was still only defined in one place.
Here, you define the volume once, e.g.:
In this example, there are no additional parameters, so the volume is only declared to exist. Any parameters are left to their default values. But you could define more properties on this volume, as needed.
Now that your volume is defined, you can use it in one container, or in multiple. You would not need to specify any of these parameters again; you’d need only to specify the path to mount the volume on, in each container.
You’ll find a similar situation with
networks
, you can define a network in thenetworks:
section, and then define numerous containers that would attach to that network. Same basic idea.