0

I have two services defined in docker-compose.yml, each one is using its own named volume.

These volumes are not pre-created. I expect docker to create the volumes after first startup of containers and re-use the same volume for further startups.

docker-compose.yml

    version: '2'
    services:
        db:
           container_name: db
           environment:
               POSTGRES_DB=new_db_name
           volumes:
               - pgdata:/var/lib/postgresql/data
        app:
           container_name: app
           depends_on:
               - db
           volumes:
               - appdata:/app/data
    volumes:
        pgdata
        appdata

However, after executing docker-compose up command, docker is prepending current directory name to volumes.

I would like docker to assign exact name specified in docker-compose yml to the volumes.

I found one solution here: https://stackoverflow.com/a/59066462/12496407

However, I am unable to apply the above solution as I have multiple volumes in my docker-compose.yml and the solution mentioned is considering only one volume.

1 Answers1

4

Since version 3.4, the name of the volume can be specified in the docker-compose file like this:

version: "3.9"
volumes:
  data:
    name: my-app-data

The name will be used as it is. For more information, please check this documentation.

So, your docker-compose should be like this:

# Make sure that the version is from 3.4
version: '3.9'
services:
  db:
    container_name: db
    environment: POSTGRES_DB=new_db_name
    volumes:
      - 'pgdata:/var/lib/postgresql/data'
  app:
    container_name: app
    depends_on:
      - db
    volumes:
      - 'appdata:/app/data'
volumes:
  pgdata:
    name: my-pgdata # Set volume name
  appdata:
    name: my-appdata # Set volume name

Triet Doan
  • 11,455
  • 8
  • 36
  • 69