Search code examples
bashdocker-compose

variable is not set error in docker-compose using bash variables


In my docker-compose I have a command like this:

version: "3.9"
...
command: "/bin/sh -c 'max=20; min=10; trap exit TERM; while :; do echo test; sleep $(($RANDOM%($max-$min+1)+$min)); done"
...

It prints test with intervals between 10 and 20 seconds. In my terminal this works just fine. In docker-compose it has issues:

WARN[0000] The "RANDOM" variable is not set. Defaulting to a blank string. 
WARN[0000] The "max" variable is not set. Defaulting to a blank string. 
WARN[0000] The "min" variable is not set. Defaulting to a blank string. 
WARN[0000] The "min" variable is not set. Defaulting to a blank string. 
WARN[0000] /..../dist/docker-compose.yml: `version` is obsolete 
1 error(s) decoding:

* error decoding 'services[tool].command': invalid command line string

It seems to have issues with these bash variables. Is there a way to fix this?


Solution

  • Create an entrypoint script entrypoint.sh and reference it in your docker-compose.yml. This approach is cleaner and separates your logic from the docker-compose.yml, making it easier to maintain and debug.

    #!/bin/sh
    
    max=20
    min=10
    trap exit TERM
    
    while :; do
      echo test
      sleep $(($RANDOM % ($max - $min + 1) + $min))
    done
    

    Make sure to make this script executable:

    chmod +x entrypoint.sh
    

    Reference the script in your docker-compose.yml

    version: "3.9"
    
    services:
      lool:
        image: image_name
        entrypoint: ["/bin/sh", "-c", "/path/to/entrypoint.sh"]