2

I have a problem with docker compose, I want to use internal conainer variables to create another another variables:

  myapp:
image: image
depends_on:
  - anotherimage
environment:
  - "VAR1=var1"
  - "VAR2=${HOSTNAME}_${VAR1}"

What I get in VAR2 the hostname of docker engine host and nothing for VAR1

I'd like to have something like:

39ed52c98e92_var1
madi
  • 160
  • 1
  • 13

1 Answers1

1

Docker-compose resolves variables in the compose file from the environment where you run the docker-compose command, not from inside the container. If you want to configure your environment from inside the container, you'll need to add this to the command or entrypoint your container runs. If you don't already have an entrypoint, you could create one as:

#!/bin/sh

export VAR2=${HOSTNAME}_${VAR1}
exec "$@"

To use that, your Dockerfile would then have two extra lines:

COPY entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]

Make sure to chmod 755 entrypoint.sh before running your docker build.


Edit: VAR1 not resolving inside your yml is a similar issue. Each variable is defined by docker-compose for the container, but that doesn't change the environment on the host that docker-compose is using. So you can't use that variable on later lines of the yml.

BMitch
  • 231,797
  • 42
  • 475
  • 450
  • This will change the source of the HOSTNAME. In the question HOSTNAME is the docker host. However in your entrypoint.sh it will resolve to the hostname of the container. Isn't it? – Robert Jun 08 '17 at 15:09
  • @Robert I believe the question says they are getting the docker host in their variable and they want the container hostname. – BMitch Jun 08 '17 at 15:10
  • see this part `and nothing for VAR1`. The problem is that in `environment:` VAR1 is not defined (there is no order in the env definitions). Do you get me? – Robert Jun 08 '17 at 15:12
  • @Robert it's not so much the order but where the variables get defined. I just realized that I didn't answer that question and updated my answer. The solution is the same for both problems. – BMitch Jun 08 '17 at 15:15
  • Ok i understand your point. Lets say i want to use the value of container HOSTNAME variable, is there a way to point to this in yml file? The goal is to set a var unique for each host in java parameters passed from yml. – madi Jun 09 '17 at 06:20
  • @madi The yml is used to create the container and doesn't have visibility backwards from the container back into the yml. If you need to pass a unique variable, you'd need to either set that outside of running compose and pass that variable through to the container, or from inside the container use the unique values you have there and create/update your entrypoint. I've made entrypoint's in the past that modified the java command making it transparent to the user. – BMitch Jun 09 '17 at 13:47