CodePark/ questions / Dockerfile instructions
START PRACTICINGPRACTICE
Backend question · Docker › Dockerfile instructions

What is the difference between ARG and ENV in a Dockerfile?

ARG is a variable for the build only. ENV is a variable that stays in the image and in every running container.

ARG defines a build-time variable: a value that exists only while the image is being built.

  • You set it with docker build --build-arg NAME=value.
  • The instructions after it can use it during the build.
  • It does not exist in the running container.

ARG also has a scope rule. An ARG declared before the first FROM can only be used in FROM lines. To use it inside a stage, you must declare it again inside that stage. Each stage needs its own declaration.

ENV sets an environment variable. It is available during the build, and Docker also stores it in the image. So every container started from that image sees it. You can override it at runtime with -e or with the Compose environment setting.

A common pattern uses both:

  • ARG NODE_VERSION to pick the base image.
  • ENV NODE_ENV=production for runtime.

Neither should hold secrets. Their values can be seen in the image metadata or the image history.

  • ARG exists only at build time, and you set it with --build-arg.
  • ENV stays in the image and in running containers.
  • You can override ENV at run time with -e.
  • Each stage needs its own ARG. An ARG before FROM only works in FROM lines.
  • Neither ARG nor ENV is safe for secrets.