前言 / Introduction

When you’re working with Docker for development or deployment, environment variables are essential. But let’s be real — it’s easy to get confused.

  • Does .env work for both build and run?
  • Why doesn’t my variable show up in the container?
  • Where should I put secrets?

This post is a personal cheat sheet of the 4 main ways I manage env vars in Docker. Hopefully, it’ll help you too 🙌

在開發的日常,使用 Docker 越發頻繁,但在使用環境變數的操作上,確實有很多坑。

所以在這篇和大家分享一些我的小筆記 - the 4 main ways I manage env vars in Docker

1. The .env File (Auto-Loaded by Compose)

The easiest and most common approach: put a .env file in the same directory as your docker-compose.yml. Docker Compose will load it automatically.

Good for quick setup in local dev.

最常見的使用方式,將 .envdocker-compose.yml 放在同個路徑底下,就會被自動讀取,既方便又簡單!


📂 Folder structure:

.
├── docker-compose.yml
└── .env

📄 .env file:

DEBUG=1
API_KEY=abc123

📄 docker-compose.yml:

services:
  web:
    image: nginx
    environment:
      - DEBUG=${DEBUG}
      - API_KEY=${API_KEY}

2. env_file: Explicitly Load Multiple Env Files

Great for multi-environment teams and keeping secrets separated.

使用在多個環境變數檔案。


If you have separate files for different environments (like dev.env, prod.env), you can load them like this:

services:
  web:
    image: nginx
    env_file:
      - .env
      - ./config/dev.env

3. Build-Time Variables: Use build.args

Best for build-only configs, like app version or feature flags.

Important: .env values are NOT automatically passed into Docker builds.

僅在將變數使用在建置場景,不需要將環境變數導入 Container 內部。


If you need a variable during build, you must pass it explicitly:

services:
  web:
    build:
      context: .
      args:
        - VERSION=${VERSION}

Inside your Dockerfile:

ARG VERSION
ENV APP_VERSION=$VERSION

Or from the command line:

docker-compose build --build-arg VERSION=1.2.3

4. CLI Overrides: Quick & Dirty for Debugging

Perfect for quick tests without touching your files.

快速複寫的方式,並且不需要對檔案修改。以及快速查閱變數的方式。


  • Sometimes, you just want to override a value on the fly:
docker-compose run -e DEBUG=1 -e MODE=testing web
  • To see all env vars in a running container:
docker-compose exec web env

My Personal Workflow

講太多了,來點的重點整理 (Takeaway)。

Here’s what I usually do:

  • 🧪 Local dev → .env + env_file
  • ⚙️ CI/CD builds → build.args
  • 🛠️ Debugging → CLI overrides
  • 🔒 Secrets → Never commit them! Use .env.template as a safe reference

Bonus Tips

一些小技巧

  • Add .env to .gitignore
  • Keep a .env.template in version control for teammates
  • Don’t store sensitive secrets in plain .env for production — consider using Docker secrets or a secret manager

Reference