ENV: Environment Variables
What You'll Learn
You'll learn how to use the ENV instruction in Dockerfiles to set environment variables that configure your containerized applications.
What Are Environment Variables in Containers?
Environment variables are key-value pairs that provide configuration to your running container. The ENV instruction in a Dockerfile sets these values during the image build process, making them available to all subsequent instructions and to the running container.
Think of environment variables like sticky notes attached to your container's workspace—they provide quick-reference information that your application can read whenever it needs configuration details.
Basic ENV Syntax
FROM ubuntu:20.04
ENV APP_ENV=production
ENV PORT=8080
You can also set multiple variables in one line:
ENV NODE_VERSION=16 \
APP_HOME=/usr/src/app
Variable Expansion
Once set, ENV variables can be referenced in subsequent Dockerfile instructions using $VARIABLE_NAME or ${VARIABLE_NAME}:
FROM node:16
ENV APP_HOME=/usr/src/app
WORKDIR $APP_HOME
COPY package.json $APP_HOME/
RUN echo "Installing to $APP_HOME"
Why Use ENV?
Environment variables separate configuration from code, allowing the same image to behave differently in development, staging, and production. Common uses include database connection strings, API keys, feature flags, and runtime behavior settings.
Variables set with ENV persist in the final image and are available when the container runs, unlike ARG which we'll cover later.
Key Takeaway: The ENV instruction sets persistent environment variables in your image that configure application behavior, support variable expansion in subsequent build steps, and remain available at container runtime for flexible configuration management.