Mandragor
Mandragor

Reputation: 5574

Can I reference the service name docker-compose.yml

In docker-compose.yaml, is there a way to reference the service name (web, database), so that in the code below, the volumes would be created as /store/web for web and /store/database for database ?

---
version: '2'

services:
  web:
    volumes:
    - /store/${reference_service_name_above}

  database:
    volumes:
    - /store/${reference_service_name_above}

Upvotes: 27

Views: 19743

Answers (3)

Dmitry Logvinenko
Dmitry Logvinenko

Reputation: 105

I suppose you can use the variable COMPOSE_PROJECT_NAME: https://docs.docker.com/compose/reference/envvars/#compose_project_name

Sets the project name. This value is prepended along with the service name to the container on start up. For example, if your project name is myapp and it includes two services db and web, then Compose starts containers named myapp_db_1 and myapp_web_1 respectively.

Upvotes: 1

kujiy
kujiy

Reputation: 6137

My answer is to extract docker-compose images.

docker-compose images | tail -n +3 | awk '{print $2}' | sed s/.*_//

This command change this return

$ docker-compose images
    Container           Repository       Tag       Image Id      Size 
----------------------------------------------------------------------
mytool_web_1   mytool_web   latest   e51243243b8c   782 MB

to this;

web

NOTE: I didn't test it on a yml which has multiple services.

Upvotes: -4

erezny
erezny

Reputation: 46

The docker-compose documentation does not provide for that.

You might want to use the common pattern of creating volumes within your stack file for use in containers.

version: "2"

services:
  web:
    volumes:
      - web-logs:/var/log/web

volumes:
  web-logs:
    external: true

https://docs.docker.com/compose/swarm/

https://docs.docker.com/compose/compose-file/#variable-substitution https://docs.docker.com/compose/compose-file/#volumes-volume-driver

Upvotes: 2

Related Questions