4

I am working on a docker-compose file, in which I need to specify container_name from an environment variable.

My docker-compose.yml file looks like this:

version: '3.0'
services:
  jenkins:
  environment:
    - INSTANCE_NAME=team_1
  image: my_image
  container_name: container_$INSTANCE_NAME
  ports:
    - "80:80"
  expose:
    - "80"

So, I think, when I run docker-compose up it should create container as name, container_team_1, but instead of that it runs as contaner_

I also tried this thing using .env file, but still, I can not use environment variable in container_name,

although, if I run docker-compose config I can see all variables set like follow,

container_name: container_
environment:
  COMPANY_NAME: team_1

but, Actually it is not attaching in container-name.

2 Answers 2

2

You cannot use environment variables defined in docker-compose.yml to variable substitution.

Docker Compose uses .env by default so it should work when you define in .env file

INSTANCE_NAME=team_1

And then run docker-compose up

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, but variable substitution get values from shell environment variables and not from .env file. From the docker-compose documentation: Compose uses the variable values from the shell environment in which docker-compose is run.
"You can set default values for environment variables using a .env file, which Compose will automatically look for. Values set in the shell environment will override those set in the .env file."
1

As I can see in variable substitution section of the docker-compose documentation, you will need to set your $INSTANCE_NAME in the shell that is running the docker-compose up, because:

Compose uses the variable values from the shell environment in which docker-compose is run.

First of all, do something like:

export INSTANCE_NAME=my_instance`

and then:

docker-compose up

Best regards.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.