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

Viewed 7310

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?

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

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 export the variable value to docker-compose or will edit the content of your variable in your .env file before calling docker-compose.

Related