Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to evaluate a dynamic variable in a docker-compose.yml file?

I want to suffix a file name with the current date in my docker-compose.yml file. The end goal being a file such as my_log_123456789.log, where 123456789 is the current unix date.

I tried using an .env file, but that did not evaluate as expected. My attempt was:

# .env
NOW="$(date +%s)"
# docker-compose.yml
version: '3.8'
services:
  xxx:
      container_name: xxx
      image: xxx/xxx
      volumes:
        - /home/ubuntu/xxx_"$(NOW)".log:/home/ubuntu/xxx.log
      ...

I tried a few variations of this and had the following issues:

  • ERROR: Invalid interpolation format for "volumes" option in service "xxx": "/home/ubuntu/xxx_$(NOW).log:/home/ubuntu/xxx.log"
  • A directory was created that was named 'xxx_"$(date +%s)".log'

How can I append the current date to a log file in a docker-compose.yml file?

like image 880
ReactHelp Avatar asked May 31 '20 19:05

ReactHelp


People also ask

Can you use variables in Docker compose file?

We can use variables in our docker-compose. yml files! The syntax is: ${SOME_VAR_NAME} . These specifically are environment variables.

Does Docker compose override environment variables?

But docker-compose does not stop at the . env and the host's current environment variables. It's cool that you can simply override values of your . env file, but this flexibility is can also be the source of nasty bugs.

How do I test a docker compose yml file?

Validating your file now is as simple as docker-compose -f docker-compose. yml config . As always, you can omit the -f docker-compose. yml part when running this in the same folder as the file itself or having the COMPOSE_FILE environment variable pointing to your file.


2 Answers

What you can do is to generate .env just before calling docker-compose:

#!/usr/bin/env bash

cat << EOF > .env
NOW=$(date +%s)
EOF

docker-compose up
like image 82
Philippe Avatar answered Oct 05 '22 21:10

Philippe


No, docker doesn't have a "dynamic" variable - the text from --env-file is read by docker as it is, literally, leading and trailing ' or " are removed, without any interpretation and expansions done by shell.

Create another script that will change the content of your variable in your .env file before calling docker-compose.

like image 28
KamilCuk Avatar answered Oct 05 '22 21:10

KamilCuk