In this lesson, you will learn how to distinguish between ARG and ENV to control configuration values during the build process versus the container runtime.
When building Docker images, you often need to inject information—like version numbers, API keys, or environment-specific settings—into your container. Docker provides two distinct instructions for this, and understanding the difference is vital for image security and flexibility.
The Build-Time Variable: ARG
The ARG instruction is used exclusively during the image build process. Think of it as a temporary parameter you pass to the docker build command to influence how the image is constructed. Once the image is built, these values "disappear"—they are not available to the application running inside the container.
ARG APP_VERSION=1.0
RUN echo "Building version $APP_VERSION"
You would set this value using docker build --build-arg APP_VERSION=2.0 .. This is perfect for settings that only matter while you are compiling code or setting up the file system.
The Runtime Variable: ENV
The ENV instruction defines variables that persist after the container has started. These values become part of the image metadata and are available to your application code while the container is running. If you want your app to know which database URL to connect to, you use ENV.
ENV DATABASE_URL="db.production.local"
Unlike ARG, ENV variables are accessible within the container shell and to the process running inside. If you change an ENV variable (for example, by overriding it at runtime with docker run -e DATABASE_URL=db.staging.local), your application will see that new value immediately.
The Comparison
ARG: Used to customize the creation of the image. It is invisible to the running container.ENV: Used to customize the behavior of the running container. It stays with the image throughout its lifecycle.
A common pattern is to use an ARG during the build to set a default, then pass that value into an ENV so the application can read it later:
ARG VERSION
ENV APP_VERSION=$VERSION
Key Takeaway: Use ARG for build-time configuration that shapes the image, and use ENV for runtime configuration that dictates how your application behaves inside the container.