Docker-compose doesn't see environement variables

I have docker-compose files that contain enviroment variables, and these are present in the shell, but when I call the docker-compose up comand, the variables are not present.

Why is this?

I know there are other ways to declare / start containers that are more nix’y, but I want to understand what is going on here.


[john@mb:~/repos/homelab/docker/glances]$ sudo docker-compose up -d
WARN[0000] The "THOR_HOST" variable is not set. Defaulting to a blank string.
WARN[0000] The "THOR_IP" variable is not set. Defaulting to a blank string.
[+] Building 0.0s (0/0)                                                                                  docker:default
[+] Running 1/0
 ✔ Container glances  Running                                                                                      0.0s

[john@mb:~/repos/homelab/docker/glances]$ sudo echo ${THOR_HOST}



  environment.variables =   {
    THOR_HOST = "mb";
    <snip some others>


version: '3'

    container_name: glances
    image: nicolargo/glances:latest-full
    restart: always
    pid: host
      - 61208:61208
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - /mnt/BlackUSB:/mnt/BlackUSB
      - /home:/home
      - "GLANCES_OPT=-w"
      - "com.centurylinklabs.watchtower.enable=true"
      - homepage.href=http://${THOR_IP}:61208
      - homepage.icon=glances.png

I’m no shell expert, but I’ve been able to in the past on nixos say “export THOR_HOME=$THOR_HOME” and have stuff like this work.

This test is incorrect, the variable expansion happens before the command is executed. Try running sudo echo ${USER}, it should print “john”, not “root”.
You can get the evaluation order you wanted like this: sudo sh -c 'echo $THOR_HOST'.

sudo does not pass your environment variables (even if exported) to the spawned process by default, there’s a flag to get around that, but I would not recommend that.

Maybe you’ll get better results by putting the relevant environment variables in a .env file alongside the docker-compose.yml, docker-compose will read that file by default to populate the environment variables.

Ah yes that’s right - thank you for enlightening me.

Yes I can use a .env file to achieve what I want, but that comes with some issues/complications in my setup.

I’ve had so many issues adapting my container setup to nixos that I’m considering setting up k3s as an easier alternative! :slight_smile: