docker-compose will always load .env

docker-compose will always load .env

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

Environment File

# .env
PORT=9879
# public.env
PORT=7000
# private.env
PORT=7001

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’