Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we need volumes inside services and volumes in docker compose file

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:
like image 381
Avv Avatar asked Oct 21 '25 05:10

Avv


1 Answers

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.

like image 81
acran Avatar answered Oct 23 '25 19:10

acran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!