clorz
clorz

Reputation: 1133

Docker compose and volumes_from by container name

I have this docker-compose.yml

version: 2.4
services:
  foo:
    image: ubuntu:focal
    container_name: oof
    volumes:
      - ./foo:/foo
  bar:
    image: ubuntu:focal
    container_name: rab
    volumes_from:
      - container:oof

With compose 1.29.2 and docker 20.10.8. But it does not start. I get an error ERROR: Service "bar" mounts volumes from "oof", which is not the name of a service or container.

How do I properly reference volumes by container name in compose?

Upvotes: 0

Views: 254

Answers (1)

David Maze
David Maze

Reputation: 159781

The best way is to explicitly spell out the volumes you're reusing. If the foo image has VOLUME directives, you'll also mount the automatically-created anonymous volumes; you also have no control over where the volumes will be mounted, and if the two containers aren't similar enough, there could be conflicts. (This is essentially the logic behind Compose file version 3 removing volumes_from:.)

version: 2.4
services:
  foo:
    volumes:
      - ./foo:/foo
  bar:
    volumes:
      - ./foo:/foo # or a different container path if that suits your needs

In general in Compose, you shouldn't need to manually specify container_name:. Compose will generate unique container names, within the docker-compose.yml file if you need to refer to things you can use the service name, and there are docker-compose wrapper commands that know how to find the right container. If you do need to use the older volumes_from: syntax use the service name instead:

version: '2.4' # does not work in version 3
services:
  foo:
    image: ...
    volumes:
      - ./foo:/foo
    # no container_name:
  bar:
    image: ...
    volumes_from: foo

Upvotes: 1

Related Questions