Home > Software design >  Why we need volumes inside services and volumes in docker compose file
Why we need volumes inside services and volumes in docker compose file

Time:09-06

I am trying to understand why we have volumes inside services in docker compose file and volumes outside services inside the same file please? Can't we just use one?

Below a durpal content management system is built with postgres database:

version: '2'

services:
  durpal:
    image: durpal
    ports:
      - '8080:80'
    volumes:
      - drupal-modules:/var/www/html/modules
      - drupal-profiles:/var/www/html/profiles
      - drupal-sites:/var/www/html/sites
      - drupal-themes:/var/www/html/themes
  postgres:
    image: postgres
    environment:
      - POSTGRES_PASSWORD = mypasswd
volumes:
  - drupal-modules:
  - drupal-profiles:
  - drupal-sites:
  - drupal-themes:

CodePudding user response:

See the official documentation: With the volumes top-level element you define named volumes to be used in that docker-compose.yml.

With the volumes service property on the other hand you specify where to mount the volumes in that container, referencing the named volumes defined in the top-level element.

The reason you (can) leave the definitions of the volumes empty is that the default values assigned for the omitted details are in most case already what you want. So only specifying the names of the volumes is enough to get them created with the default configurations. Look at the volumes top-level element documentation to see what other configurations are available.

To learn more about volumes see this page in the documentation.

  • Related