docker-compose will always load .env

Jonah Yeoh - May 30 - - Dev Community

Update 6th-Jun-2024

After deeper dive into the docs and practice. I realize I mixed up .env and file.env. Please refer to -> https://dev.to/tbroyer/comment/2fhdp, that's the right way of understanding this concept.

Screenshot of the issue I am presenting in one glance

As shown in the screenshot, I didn't specify .env under any env_file directives. But it choose to use the PORT value defined under .env instead of public.env or private.env.

Versions

  • docker: 24.0.0
  • docker-compose: 1.29.2

Possible Solution

  • Remove '.env'
  • Never use variable names that are already defined in .env

My Take

I think more people should be aware of this default behavior and I am interested to know how others deal with this issue.

Code Snippet

Checkout the code snippet below if the screenshot is not clear.

# docker-compose.yml
version: "3.8"

services:
  private:
    container_name: private_server
    build: ./backend
    command: uvicorn main:app --host=0.0.0.0 --port=7000
    ports:
      # - 127.0.0.1:${PUBLIC_PORT}:7000
      - 127.0.0.1:${PORT:-7001}:7000
    environment:
      - WORKSPACE=secret
    env_file:
      - private.env

  public:
    container_name: public_server
    build: ./backend
    command: uvicorn main:app --host=0.0.0.0 --port=7000
    ports:
      # - 127.0.0.1:${PRIVATE_PORT}:7000
      - 127.0.0.1:${PORT:-7000}:7000
    environment:
      - WORKSPACE=client
    env_file:
      - public.env
Enter fullscreen mode Exit fullscreen mode

Environment File

# .env
PORT=9879
Enter fullscreen mode Exit fullscreen mode
# public.env
PORT=7000
Enter fullscreen mode Exit fullscreen mode
# private.env
PORT=7001
Enter fullscreen mode Exit fullscreen mode

docker-compose config

services:
  private:
    build:
      context: /home/server/projects/server/backend
    command: uvicorn main:app --host=0.0.0.0 --port=7000
    container_name: private_server
    environment:
      PORT: '7001'
      WORKSPACE: secret
    ports:
    - 127.0.0.1:9879:7000/tcp
  public:
    build:
      context: /home/server/projects/server/backend
    command: uvicorn main:app --host=0.0.0.0 --port=7000
    container_name: public_server
    environment:
      PORT: '7000'
      WORKSPACE: client
    ports:
    - 127.0.0.1:9879:7000/tcp
version: '3.8'
Enter fullscreen mode Exit fullscreen mode
.