Joey Yi Zhao
Joey Yi Zhao

Reputation: 42596

How to share volumes among containers by docker-compose

My docker-compose defines two containers. I want one container shares a volume to the other container.

version: '3'
services:
  web-server:
    env_file: .env
    container_name: web-server
    image: web-server
    build: 
      dockerfile: docker/Dockerfile
    ports: 
      - 3000:3000
      - 3500:3500
    volumes:
      - static-content: /workspace/static
    command: sh /workspace/start.sh

  backend-server:
    volumes:
      - static-content: /workspace/static
  volumes:
    static-content:

The above docker composer file declares two services, web-server and backend-server. And I declares the named volume static-content under services. I got below error when I run docker-composer -f docker-composer.yml up:

services.web-server.volumes contains an invalid type, it should be a string
services.backend-server.volumes contains an invalid type, it should be a string

so how can I share volumes throw docker-composer?

Upvotes: 5

Views: 14494

Answers (2)

BMitch
BMitch

Reputation: 264861

You have an extra space in your volume string that causes Yaml to change the parsing from an array of strings to an array of name/value maps. Remove that space in your volume entries (see below) to prevent this error:

version: '3'
services:
  web-server:
    env_file: .env
    container_name: web-server
    image: web-server
    build: 
      dockerfile: docker/Dockerfile
    ports: 
      - 3000:3000
      - 3500:3500
    volumes:
      - static-content:/workspace/static
    command: sh /workspace/start.sh

  backend-server:
    volumes:
      - static-content:/workspace/static
  volumes:
    static-content:

For more details, see the compose file section on volumes short syntax.

Upvotes: 3

adimor
adimor

Reputation: 36

You need to use the docker volumes syntax, without spaces

<local_path>:<service_path>:<optional_rw_attributes>

For example:

./:/your_path/

will map the present working directory to /your_path

And this example:

./:/your_path/:ro

will map the present working directory to /your_path with read only permissions

Read these docs for more info: https://docs.docker.com/compose/compose-file/#volume-configuration-reference

Upvotes: 2

Related Questions