Lesson 2 of 9 ↓
- 1.Docker Comprehensive Guide: From Zero to Hero
- 2.Docker Environment Variables: the Ultimate Guide
- 3.Docker Images: the Ultimate Comprehensive Guide
- 4.Docker: Cmd vs. Entrypoint - the Comprehensive Guide
- 5.Docker Networking: the Ultimate Deep Dive
- 6.Docker Storage & Filesystem: the Complete Reference
- 7.Docker Compose: the Ultimate Master Guide
- 8.Docker Registry: the Ultimate Master Guide
- 9.Docker Engine: the Ultimate Deep Dive
4 min read
Docker Environment Variables: the Ultimate Guide
This guide is designed to take you from a beginner to an expert in handling Environment Variables in Docker. It covers how to inject configuration data into containers without changing the source code.
Why Environment Variables?
Before diving into commands, you must understand the "Why". Imagine you have a Web Application connecting to a Database.
-
Hardcoding: If you write the database password inside the code (
app.py), you have to edit the code and rebuild the image every time the password changes. This is bad practice. -
Environment Variables: You write the code to look for a variable (e.g.,
DB_PASSWORD). You pass the actual password only when you run the container. This is the Docker way.
Passing Variables: the -e Flag
The most common way to pass a variable is using the -e (or --env) flag during docker run.
Single Variable
Command:
docker run -e APP_COLOR=blue simple-webappMultiple Variables
Command:
docker run -e APP_COLOR=green -e DEBUG_MODE=true simple-webappPassing Host Variables
If you already have a variable exported in your current terminal (Host machine), you can pass it directly without typing the value. Command:
export API_KEY=123456
docker run -e API_KEY my-script- Explanation: Docker looks for
API_KEYon your machine and passes its value (123456) into the container.
Key Arguments Breakdown
| Argument | Full Name | Importance | Description |
|---|---|---|---|
-e |
--env |
Critical | Sets a specific environment variable inside the container. |
KEY=VALUE |
- | Critical | The format must be strictly KEY=VALUE (no spaces around =). |
The Professional Way: --env-file
If you have 10 or 20 variables, the docker run command becomes huge and messy. The solution is to use an environment file.
Step 1: Create a file named .env
APP_COLOR=pink
DB_HOST=mysql
DB_USER=root
DB_PASS=secretStep 2: Run Docker with the file Command:
docker run --env-file .env simple-webappKey Arguments Breakdown
| Argument | Importance | Description |
|---|---|---|
--env-file |
High | Reads a local text file and injects all variables defined in it into the container. Keeps your CLI command clean and secure. |
Inspecting Variables: docker Inspect
How do you check if the variables were successfully passed to a container? You use the inspect command (as shown in your screenshots).
Command:
docker inspect <container_id_or_name>Understanding the Output: This command returns a huge JSON object. You need to look for the Config section.
Example Snippet (from docker inspect):
"Config": {
"Hostname": "35505f7810d1",
"Env": [
"APP_COLOR=blue",
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"PYTHON_VERSION=3.6.6"
],
"Image": "simple-webapp",
...
}- Note: The
Envarray lists all variables available to the application inside the container.
Checking Inside the Container
Sometimes inspect isn't enough. You want to see what the running container actually sees.
Command:
docker exec -it <container_id> env
# OR
docker exec -it <container_id> printenv- Explanation: This runs the Linux command
envorprintenvinside the container, listing all active variables immediately.
Dockerfile: env vs arg (crucial Concept)
When building images, there are two ways to set variables. This is a common interview question and a source of confusion.
env (environment Variable)
-
Usage:
ENV APP_PORT=8080 -
Lifecycle: Available during the build AND available to the container when it runs.
-
Overridable: Yes, using
docker run -e APP_PORT=9090.
arg (build Argument)
-
Usage:
ARG VERSION=1.0 -
Lifecycle: Available ONLY during the build process (e.g., to download a specific version). It dies after the image is built. It is NOT available to the running container.
-
Overridable: Yes, using
docker build --build-arg VERSION=2.0 .
Summary Table: | Instruction | Available at Build Time? | Available at Run Time? | Used for... | | :--- | :---: | :---: | :--- | | ARG | ✅ YES | ❌ NO | Version numbers, installer options. | | ENV | ✅ YES | ✅ YES | DB Hosts, API Keys, App Configuration. |
Real World Scenario: the Python Flask App
This example is based on the "Simple WebApp" from your PDF.
The Python Code (app.py)
This code uses the os library to fetch the variable.
import os
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def main():
# Logic: Look for 'APP_COLOR'. If not found, default to 'red'
color = os.environ.get('APP_COLOR', 'red')
return render_template('hello.html', color=color)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8080)The Dockerfile
FROM python:3.6-alpine
# Install Flask
RUN pip install flask
# Set a Default Environment Variable (Optional)
# This will be used if the user doesn't provide one with -e
ENV APP_COLOR=red
COPY . /opt/
ENTRYPOINT ["python", "/opt/app.py"]Running the Scenarios
Scenario 1: Default (Red)
docker run -d -p 8080:8080 simple-webapp- Result: The app sees
APP_COLOR=red(from Dockerfile). Background is Red.
Scenario 2: Blue Override
docker run -d -p 8081:8080 -e APP_COLOR=blue simple-webapp- Result: The
-eflag overrides the Dockerfile. Background is Blue.
Scenario 3: Green Override
docker run -d -p 8082:8080 -e APP_COLOR=green simple-webapp
Comments
Loading the discussion…