Bird
Raised Fist0
Dockerdevops~15 mins

ARG and ENV instructions in Docker - Deep Dive

Choose your learning style10 modes available
Overview - ARG and ENV instructions
What is it?
ARG and ENV are instructions used in Dockerfiles to define variables. ARG sets build-time variables that exist only while building the image. ENV sets environment variables that persist in the running container. These variables help customize the image and container behavior without hardcoding values.
Why it matters
Without ARG and ENV, Docker images would be rigid and hard to customize. Developers would need to create many images for small changes or manually configure containers after starting them. ARG and ENV make images flexible, reusable, and easier to maintain, saving time and reducing errors.
Where it fits
Learners should know basic Dockerfile structure and image building before this. After mastering ARG and ENV, they can learn about Docker Compose, multi-stage builds, and container runtime configuration for advanced container management.
Mental Model
Core Idea
ARG defines temporary build-time variables, while ENV defines persistent runtime environment variables inside Docker containers.
Think of it like...
ARG is like a recipe note you use only while cooking, but ENV is like a label on the finished dish that tells you how to serve it.
Dockerfile
├── ARG <name>=<default>  (build-time variable, temporary)
├── ENV <name>=<value>    (runtime variable, persistent)
|
Build phase: ARG used only here
|
Run phase: ENV available inside container
Build-Up - 7 Steps
1
FoundationUnderstanding ARG basics
🤔
Concept: ARG defines variables available only during image build.
In a Dockerfile, ARG lets you declare a variable with an optional default value. You can use it in later instructions during build. For example: ARG VERSION=1.0 RUN echo "Building version $VERSION" This prints the version during build but the variable is not in the final image.
Result
The build output shows 'Building version 1.0'. The variable VERSION is not available after build.
Understanding ARG helps you customize builds without affecting the final container environment.
2
FoundationUnderstanding ENV basics
🤔
Concept: ENV sets environment variables that exist inside the running container.
ENV defines variables that persist in the container after it starts. For example: ENV APP_ENV=production Inside the container, any process can read APP_ENV. This helps configure app behavior at runtime.
Result
When the container runs, the environment variable APP_ENV is set to 'production'.
Knowing ENV lets you control container behavior dynamically without changing the image.
3
IntermediateUsing ARG with docker build command
🤔Before reading on: Do you think ARG variables can be overridden during docker build? Commit to your answer.
Concept: ARG variables can be overridden at build time using --build-arg option.
You can pass a different value for ARG when building: docker build --build-arg VERSION=2.0 . This overrides the default VERSION=1.0 in the Dockerfile. The build uses VERSION=2.0 instead.
Result
The build output shows 'Building version 2.0' instead of the default.
Knowing how to override ARG at build time makes your builds flexible and reusable.
4
IntermediateENV variables can use ARG values
🤔Before reading on: Can ENV variables be set using ARG values? Commit to your answer.
Concept: You can use ARG values to set ENV variables during build, combining build-time and runtime configs.
Example: ARG VERSION=1.0 ENV APP_VERSION=$VERSION This sets APP_VERSION inside the container to the build-time VERSION value.
Result
Inside the container, APP_VERSION is set to the value passed to VERSION during build.
Combining ARG and ENV lets you pass build-time info into the running container environment.
5
IntermediateScope and lifetime differences
🤔
Concept: ARG variables exist only during build; ENV variables exist in the container runtime.
ARG variables disappear after build finishes. ENV variables stay in the image and container. For example, you cannot access ARG inside a running container, but ENV is always accessible.
Result
Trying to echo an ARG variable inside a running container returns empty, but ENV variables show their values.
Understanding variable lifetimes prevents confusion about where and when variables are accessible.
6
AdvancedSecurity considerations with ARG and ENV
🤔Before reading on: Do you think ARG and ENV variables are secure ways to store secrets? Commit to your answer.
Concept: ARG and ENV are not secure for secrets because they can be inspected in image history or container environment.
ARG values appear in image build history and ENV variables are visible inside containers. For secrets, use Docker secrets or external vaults instead.
Result
Secrets stored in ARG or ENV can be exposed unintentionally, risking security breaches.
Knowing the security limits of ARG and ENV helps avoid accidental leaks of sensitive data.
7
ExpertSubtle behavior with multi-stage builds
🤔Before reading on: Does ARG persist across multi-stage builds automatically? Commit to your answer.
Concept: ARG variables must be re-declared in each build stage; they do not automatically carry over.
In multi-stage Dockerfiles: FROM base AS builder ARG VERSION=1.0 FROM base AS final # VERSION is not available here unless re-declared ARG VERSION ENV APP_VERSION=$VERSION You must declare ARG in each stage to use it.
Result
Without re-declaring ARG, the variable is empty in later stages, causing unexpected behavior.
Understanding ARG scope in multi-stage builds prevents subtle bugs in complex Dockerfiles.
Under the Hood
During docker build, ARG variables are substituted by the Docker engine only in the build context. They do not become part of the image layers. ENV variables are written into image metadata and become part of the container's environment when it runs. The Dockerfile parser processes ARG first, then ENV, resolving variables accordingly.
Why designed this way?
Separating build-time and runtime variables allows flexibility and security. Build-time variables customize image creation without bloating the image or exposing sensitive data at runtime. Runtime variables configure container behavior dynamically. This design balances customization and image size.
Docker Build Process
┌───────────────┐
│ Dockerfile    │
│ ┌───────────┐ │
│ │ ARG VARS  │ │  <-- Used only during build
│ └───────────┘ │
│ ┌───────────┐ │
│ │ ENV VARS  │ │  <-- Stored in image metadata
│ └───────────┘ │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Docker Image  │
│ ENV variables │  <-- Available at container runtime
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Can ARG variables be accessed inside a running container? Commit yes or no.
Common Belief:ARG variables are available inside the running container just like ENV variables.
Tap to reveal reality
Reality:ARG variables exist only during build and are not present in the running container environment.
Why it matters:Assuming ARG is available at runtime leads to bugs where expected variables are missing inside containers.
Quick: Are ENV variables secure places to store passwords? Commit yes or no.
Common Belief:ENV variables are safe to store secrets like passwords or API keys.
Tap to reveal reality
Reality:ENV variables can be viewed by anyone with container access or by inspecting the image, so they are not secure for secrets.
Why it matters:Storing secrets in ENV risks accidental exposure and security breaches.
Quick: Do ARG variables automatically carry over between multi-stage build stages? Commit yes or no.
Common Belief:ARG variables declared in one stage are automatically available in all subsequent stages.
Tap to reveal reality
Reality:ARG variables must be declared in each stage separately; they do not persist across stages automatically.
Why it matters:Not re-declaring ARG in each stage causes empty or missing variables, leading to build failures or wrong configurations.
Quick: Does setting ENV overwrite ARG values during build? Commit yes or no.
Common Belief:ENV variables override ARG variables if they have the same name.
Tap to reveal reality
Reality:ARG and ENV are separate; ENV can use ARG values but does not overwrite ARG. ARG is only build-time, ENV is runtime.
Why it matters:Confusing ARG and ENV leads to unexpected variable values and container behavior.
Expert Zone
1
ARG variables can be used to reduce image size by conditionally including build steps, but misuse can cause cache invalidation.
2
ENV variables set in Dockerfile can be overridden at container runtime with docker run -e, allowing flexible container configuration.
3
Using ARG in combination with multi-stage builds requires careful re-declaration to avoid subtle bugs in complex images.
When NOT to use
Do not use ARG or ENV to store sensitive secrets; use Docker secrets or external vaults instead. Avoid ARG for runtime configuration since it is not available after build. For dynamic runtime configs, prefer ENV or external config files.
Production Patterns
In production, ARG is often used to pass build versions or flags, while ENV configures app modes (dev, prod). Multi-stage builds use ARG to control build dependencies. ENV variables are overridden at runtime for environment-specific settings without rebuilding images.
Connections
Environment Variables in Operating Systems
ARG and ENV in Docker mirror OS environment variables but differ in scope and lifetime.
Understanding OS environment variables helps grasp how ENV configures container processes similarly.
Build-Time vs Runtime Configuration
ARG represents build-time config, ENV represents runtime config, illustrating a common software deployment pattern.
Knowing this separation clarifies why some settings must be fixed at build and others remain flexible at runtime.
Software Compilation Flags
ARG is like compile-time flags in programming languages that affect how software is built but not how it runs.
Recognizing this analogy helps understand why ARG variables do not persist after build.
Common Pitfalls
#1Trying to access ARG variables inside a running container.
Wrong approach:docker run myimage sh -c 'echo $VERSION' # expecting ARG VERSION here
Correct approach:Use ENV to set variables for runtime: ENV VERSION=1.0 Then run: docker run myimage sh -c 'echo $VERSION'
Root cause:Misunderstanding that ARG is only for build-time and not included in container environment.
#2Not re-declaring ARG in each stage of a multi-stage build.
Wrong approach:FROM base AS builder ARG VERSION=1.0 FROM base AS final # no ARG VERSION here ENV APP_VERSION=$VERSION
Correct approach:FROM base AS builder ARG VERSION=1.0 FROM base AS final ARG VERSION ENV APP_VERSION=$VERSION
Root cause:Assuming ARG variables persist across stages without explicit declaration.
#3Storing sensitive secrets in ENV variables.
Wrong approach:ENV DB_PASSWORD=supersecret
Correct approach:Use Docker secrets or external vaults to manage sensitive data securely.
Root cause:Believing ENV variables are private and secure inside containers.
Key Takeaways
ARG variables are only available during image build and cannot be accessed inside running containers.
ENV variables persist in the image and container, configuring runtime behavior dynamically.
ARG can be overridden at build time with --build-arg, making builds flexible and reusable.
In multi-stage builds, ARG must be declared in each stage to be accessible.
Neither ARG nor ENV should be used to store secrets; use dedicated secret management tools instead.

Practice

(1/5)
1. What is the main difference between ARG and ENV instructions in a Dockerfile?
easy
A. ARG defines build-time variables, ENV defines runtime environment variables.
B. ARG defines runtime environment variables, ENV defines build-time variables.
C. ARG and ENV are exactly the same and interchangeable.
D. ARG is used to set default ports, ENV sets user permissions.

Solution

  1. Step 1: Understand ARG usage

    ARG defines variables that are only available during the image build process. They cannot be accessed after the image is built.
  2. Step 2: Understand ENV usage

    ENV sets environment variables that persist in the built image and are available at runtime inside containers.
  3. Final Answer:

    ARG defines build-time variables, ENV defines runtime environment variables. -> Option A
  4. Quick Check:

    ARG = build-time, ENV = runtime [OK]
Hint: Remember: ARG is build-time, ENV is runtime [OK]
Common Mistakes:
  • Confusing ARG as runtime variable
  • Thinking ENV variables are only for build-time
  • Assuming ARG persists in the final image
  • Mixing up the purpose of ARG and ENV
2. Which of the following is the correct syntax to declare a build argument named VERSION with a default value 1.0 in a Dockerfile?
easy
A. ARG VERSION : 1.0
B. ENV VERSION=1.0
C. ARG VERSION=1.0
D. ENV VERSION : 1.0

Solution

  1. Step 1: Recall ARG syntax

    The correct syntax to declare a build argument with a default value is ARG name=value. So ARG VERSION=1.0 is valid.
  2. Step 2: Check other options

    ENV is for environment variables, not build arguments. The colon syntax is invalid in Dockerfile.
  3. Final Answer:

    ARG VERSION=1.0 -> Option C
  4. Quick Check:

    ARG syntax uses equals sign (=) [OK]
Hint: ARG uses '=' to assign default values [OK]
Common Mistakes:
  • Using ENV instead of ARG for build arguments
  • Using colon (:) instead of equals (=)
  • Omitting the default value syntax
  • Confusing ARG and ENV syntax
3. Given the Dockerfile snippet:
ARG APP_VERSION=2.0
ENV APP_VERSION=$APP_VERSION
RUN echo $APP_VERSION

What will be the output of the RUN echo $APP_VERSION command during build if no build argument is passed?
medium
A. Error: variable not found
B. $APP_VERSION
C. empty line
D. 2.0

Solution

  1. Step 1: Understand ARG default value

    ARG APP_VERSION=2.0 sets a default build argument value of "2.0" if none is passed.
  2. Step 2: ENV uses ARG value

    ENV APP_VERSION=$APP_VERSION sets an environment variable using the ARG value, so it becomes "2.0".
  3. Step 3: RUN command output

    RUN echo $APP_VERSION prints the environment variable value "2.0" during build.
  4. Final Answer:

    2.0 -> Option D
  5. Quick Check:

    ARG default used in ENV, echoed as 2.0 [OK]
Hint: ARG default flows into ENV if no override [OK]
Common Mistakes:
  • Expecting empty output if no build arg passed
  • Thinking $APP_VERSION is literal string
  • Assuming error if variable not passed
  • Confusing build-time and runtime variable scopes
4. Identify the error in this Dockerfile snippet:
ARG PORT
ENV PORT=8080
EXPOSE $PORT
medium
A. You cannot use variables in the EXPOSE instruction.
B. The ENV variable PORT overrides ARG but EXPOSE uses $PORT which is not expanded.
C. The ARG variable PORT is not given a default value.
D. The ENV instruction must come before ARG.

Solution

  1. Step 1: Check variable usage in EXPOSE

    The EXPOSE instruction does not support variable expansion. Using $PORT will not work.
  2. Step 2: Validate other statements

    Not giving a default to ARG PORT is allowed. ENV can override ARG. The order of ARG and ENV is not restricted.
  3. Final Answer:

    You cannot use variables in the EXPOSE instruction. -> Option A
  4. Quick Check:

    EXPOSE does not expand variables [OK]
Hint: EXPOSE needs literal port numbers, no variables allowed [OK]
Common Mistakes:
  • Assuming EXPOSE supports variable expansion
  • Thinking ARG must have default value
  • Believing ENV must come after ARG
  • Confusing build-time and runtime variable scopes
5. You want to build a Docker image that accepts a build argument APP_ENV with default production and sets an environment variable APP_ENV inside the container accordingly. Which Dockerfile snippet correctly achieves this?
hard
A. ENV APP_ENV=production ARG APP_ENV ENV APP_ENV=$APP_ENV
B. ARG APP_ENV=production ENV APP_ENV=$APP_ENV
C. ARG APP_ENV ENV APP_ENV=production
D. ENV APP_ENV=$APP_ENV ARG APP_ENV=production

Solution

  1. Step 1: Set ARG with default value

    ARG APP_ENV=production defines the build argument with default "production" if none is passed.
  2. Step 2: Set ENV using ARG value

    ENV APP_ENV=$APP_ENV sets the runtime environment variable to the ARG value, so it reflects the build argument or default.
  3. Step 3: Validate other options

    ENV APP_ENV=production ARG APP_ENV ENV APP_ENV=$APP_ENV sets ENV before ARG which is invalid. ARG APP_ENV ENV APP_ENV=production does not set default for ARG. ENV APP_ENV=$APP_ENV ARG APP_ENV=production uses ENV before ARG which is incorrect.
  4. Final Answer:

    ARG APP_ENV=production ENV APP_ENV=$APP_ENV -> Option B
  5. Quick Check:

    ARG default then ENV from ARG [OK]
Hint: Declare ARG with default, then ENV using ARG variable [OK]
Common Mistakes:
  • Setting ENV before ARG
  • Not providing default value for ARG
  • Overwriting ENV without ARG reference
  • Confusing build-time and runtime variable order
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard