Home > database >  Why do I need to specify volumes twice?
Why do I need to specify volumes twice?

Time:06-14

I've read this post and this one. And the best explanation I've dound 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.

CodePudding user response:

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.:

volumes:
  db-data:

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.

volumes:
  db-data:
    driver_opts:
      type: "nfs"
      o: "addr=10.0.0.10,rw"

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.

services:
  foo:
    image: awesome/database
    volumes:
      - db-data:/etc/data

  bar:
    image: awesome/database
    volumes:
      - db-data:/var/data

volumes:
  db-data:

You'll find a similar situation with networks, you can define a network in the networks: section, and then define numerous containers that would attach to that network. Same basic idea.

CodePudding user response:

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.

  • Related