env-file
- Docker & Kubernetes course
- Beginner
- Lesson 58/82
- 4 min
Learn to load variables from a file with --env-file.
--env-file
Instead of writing many variables one by one with -e, they are collected in a file. Each line has the form NAME=value; lines starting with # are comments. Values aren't quoted (the quotes become part of the value):
# app.env
DB_HOST=db
DB_PORT=5432
DB_USER=app
LOG_LEVEL=info
docker run -d --env-file app.env api:1.0Order and secrecy
--env-file and -e can be used together; if the same variable is in both, -e wins. Env files containing secret values aren't put under version control; a sample file without values is shared instead:
docker run -d --env-file app.env -e LOG_LEVEL=debug api:1.0
# .gitignore
app.env
# sample put in the repo: app.env.ornek
DB_PASSWORD=Practice An env file
Write the contents of the app.env file: DB_HOST=db, DB_PORT=5432, LOG_LEVEL=info (each on its own line). On the last line, write the command starting a container named api from api:1.0 in the background using this file.
Starter code
# app.env
# buraya yazSample solution
# app.env
DB_HOST=db
DB_PORT=5432
LOG_LEVEL=info
docker run -d --name api --env-file app.env api:1.0Expected output
a3b4c5d6e7f8
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 If LOG_LEVEL="info" is written in app.env, what is the value in the container?
- It errors
- "info" (with the quotes) Correct answer
- info
- Empty
Explanation: docker run --env-file doesn't strip quotes; Compose's .env reading does.
2 Read the variables from a file.
docker run -d ____ app.env api:1.0
docker run -d --env-file app.env api:1.0
Explanation: --env-file loads each line as a variable.
3 Match.
| Term | Meaning |
|---|---|
NAME=value |
One line |
# comment |
Ignored |
conflict with -e |
-e wins |
app.env.ornek |
Shared sample |