What is ENV in Dockerfile: Definition and Usage
ENV instruction in a Dockerfile sets environment variables inside the Docker image. These variables can be used to configure the container's behavior or pass configuration data during runtime.How It Works
The ENV instruction in a Dockerfile works like setting up labels or notes inside a container that programs can read while running. Imagine you are packing a lunchbox and you write a note inside with instructions or preferences. Similarly, ENV sets key-value pairs that the container can use as settings.
When you build a Docker image, each ENV line adds an environment variable that stays inside the image. Later, when you run a container from that image, these variables are available to any program inside the container, just like reading a note you left earlier.
Example
This example shows how to set an environment variable APP_MODE to production inside a Dockerfile.
FROM alpine:latest ENV APP_MODE=production CMD ["sh", "-c", "echo Running in $APP_MODE mode"]
When to Use
Use ENV when you want to provide configuration values that your application or scripts inside the container need to run properly. For example, setting database URLs, API keys, or mode flags like development or production.
This helps keep your Docker images flexible and reusable because you can change behavior without modifying the code, just by changing environment variables.
Key Points
- ENV sets environment variables inside the Docker image.
- Variables are available to all processes running in the container.
- It helps configure container behavior without changing code.
- Values set by
ENVpersist in the image and containers made from it.
Key Takeaways
ENV sets environment variables inside Docker images for container configuration.ENV are accessible to all processes in the container.ENV to keep images flexible by separating configuration from code.ENV persist in the image and affect all containers created from it.