Search code examples
dockerdocker-composedocker-container

How to set environment variables in docker-compose


I have a docker-compose file in which I use env_file to read and set a bunch of env variables at run time. These env variables are required for a command that I need to run at run time using command. However it looks like the command section is executed before the env variables are set at run time and this cause an error. How can I ensure that setting the env variables occur before executing the command section in a docker-compose?

Here is my docker-compose file

services:
  mlx-python-hdfs:
    image: image_name
    container_name: cname
    env_file: ./variables.txt
    command:
         - microservice $VAR1 $VAR2

$VAR1 and $VAR2 are read from variables.txt file but when I start the container it complains on "microservice $VAR1 $VAR2" line and show the $VAR1 and VAR2 as empty.


Solution

  • rename your file to .env (without name) so mv variables.txt .env

    edit your compose :

    services:
      mlx-python-hdfs:
        image: image_name
        container_name: cname
        command:
             - microservice $VAR1 $VAR2
    

    then run it normally see this