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

← All Docker questions