BudiBadu Logo
Samplebadu

Dockerfile by Example: Environment Variable Definition

Docker Engine 20.10+

The ENV instruction sets environment variables that persist when the container runs. This code example shows how to set configuration defaults and path variables.

Code

FROM node:18-alpine

# Set a single environment variable
ENV NODE_ENV=production

# Set multiple variables at once (cleaner syntax)
ENV APP_PORT=3000     LOG_LEVEL=info     API_URL="https://api.example.com"

# Use variables in subsequent instructions
WORKDIR /app
EXPOSE $APP_PORT

CMD ["node", "server.js"]

Explanation

The ENV instruction defines environment variables that are available both during the build process and in the running container. Unlike ARG, which is build-time only, ENV values persist in the final image and can be inspected via docker inspect. These variables are accessible to the application code at runtime (e.g., process.env in Node.js) and to subsequent instructions in the Dockerfile.

Environment variable characteristics include:

  • Persist in the final image and running container
  • Can be overridden at runtime using docker run -e
  • Visible in docker history and image metadata
  • Support variable substitution in subsequent Dockerfile instructions

While ENV is standard for defining default configurations like ports or log levels, it poses a security risk for sensitive data. Secrets such as API keys or passwords should never be stored in ENV instructions because they are permanently baked into the image layers and can be easily extracted. For sensitive information, runtime mechanisms like Docker Secrets or mounted environment files are the secure alternatives.

Code Breakdown

4
ENV NODE_ENV=production sets a persistent variable for the container.
7
Backslashes allow defining multiple variables in a single instruction.
13
EXPOSE $APP_PORT demonstrates variable substitution within the Dockerfile.
15
CMD executes the server, which can read these variables from its environment.