Docker interview question · Most asked
ARG or ENV: what is the difference, and how do you pass secrets into a build safely?
Summary
ARG defines build-time variables available only while building (set with --build-arg); ENV sets environment variables persisted in the image and present at runtime. Neither is safe for secrets: build args can appear in image history and metadata, and ENV values are stored in the image.
Longer Answer
Use BuildKit secret mounts: RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci, passed with docker build --secret id=npmrc,src=$HOME/.npmrc. The secret is available only during that RUN step and never written to a layer. For SSH access to private repositories, use --mount=type=ssh. Runtime secrets belong in the orchestrator's secret mechanism, not the image.
Code Example
# syntax=docker/dockerfile:1
RUN --mount=type=secret,id=npm_token \
NPM_TOKEN=$(cat /run/secrets/npm_token) npm ci
Key Points
- ARG: build-time; ENV: persisted runtime.
- Neither is safe for secrets.
- BuildKit --mount=type=secret.
- Runtime secrets from the orchestrator.
More most-asked Docker questions
- How do you secure Docker containers and images?
- What is a container, and how does it differ from a virtual machine?
- What is the difference between an image and a container, and how do image layers work?
- CMD or ENTRYPOINT: what is the difference, and what are exec and shell forms?
- How does Docker build caching work, and how do you order a Dockerfile to use it well?
- What are Dockerfile best practices for production images?
- What are multi-stage builds, and why use them?
- How do you make Docker images smaller?