dockerdocker-compose

Can you use the current project_name in a docker compose file?


I see lots of questions around setting/changing the COMPOSE_PROJECT_NAME or PROJECT_NAME using ENV variables.

I'm fine with the default project name, but I would like to reference it in my compose file.

version: "3.7"
services:
  app:
    build: DockerFile
    container_name: app
    volumes:
      - ./:/var/app
    networks:
      - the-net

  npm:
    image: ${project_name}_app
    volumes:
      - ./:/var/app
    depends_on:
      - app
    entrypoint: [ 'npm' ]
    networks:
     - the-net

npm here is arbitrary , hopefully the fact that could be run as its own container or in other ways does not distract from the questions.

is it possible to reference the project name with out setting it manually or first?


Solution

  • Edit: This is now possible, and the documentation for the COMPOSE_PROJECT_NAME has been updated:

    services:
      test:
        image: "alpine:latest"
        container_name: "${COMPOSE_PROJECT_NAME}_alpine_container"
        command: [ "echo", "Hello ${COMPOSE_PROJECT_NAME}" ]
    
    $ export COMPOSE_PROJECT_NAME=stackoverflow
    $ docker compose up
    [+] Building 0.0s (0/0)                                                                                               docker:default
    [+] Running 2/2
     ✔ Network stackoverflow_default             Created                                                                            0.0s
     ✔ Container stackoverflow_alpine_container  Created                                                                            0.1s
    Attaching to stackoverflow_alpine_container
    stackoverflow_alpine_container  | Hello stackoverflow
    stackoverflow_alpine_container exited with code 0
    

    Original Answer

    Unfortunately it is not possible.

    As alluded to, you can create a .env file and populate it with COMPOSE_PROJECT_NAME=my_name, but the config option does not present itself in your environment by default.

    Unfortunately the env substitution in docker-compose is fairly limited, meaning we cannot use the available PWD env variable and greedy match it at all

    $ cd ~
    $ pwd
    /home/tqid
    $ echo "Base Dir: ${PWD##*/}"
    Base Dir: tqid
    

    When we use this reference, compose has issues:

    $ docker-compose up -d
    ERROR: Invalid interpolation format for "image" option in service "demo": "${PWD##*/}"
    

    It's probably better to be explicit anyway, the COMPOSE_PROJECT_NAME is based on your dir, and if someone clones to a new folder then it gets out of whack, including the .env file in source control would provide a re-usable and consistent place to reference the name

    https://docs.docker.com/compose/reference/envvars/#compose_project_name