iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐳

Passing Environment Variables with Dockerfile ENV (Including Differences from ARG)

に公開

Use ENV in Dockerfile to Set Environment Variables

To pass environment variables to a container in a Dockerfile, you use ENV.

Here is how to use it.

How to Use ENV

1. Create a Dockerfile

This is how you write the Dockerfile.

FROM centos

ENV SITE_DOMAIN "example.com"

With this, the environment variable SITE_DOMAIN will contain example.com within the built image.

2. Build the Dockerfile

Command to build the Dockerfile.

docker build -t centos-custom:0.1 .

Now, the environment variable is embedded within the finished image.

Use -e to Change Initial Values during run

When you want to change the value set in the Dockerfile, you can pass it using -e.

docker container run \
  -d \
  -e SITE_DOMAIN="example.net" centos-custom:0.1

In the example above, SITE_DOMAIN, which was example.com in the Dockerfile, has been changed to example.net.

Set the PATH Environment Variable with ENV in a Dockerfile

You can also set the PATH environment variable using ENV in a Dockerfile.

You can use ENV to update the PATH environment variable for software your container installs, so it's easy for your software to run.

ENV | Dockerfile best practices | Docker Documentation

For example, you can add nginx to the PATH with the following code.

ENV PATH /usr/local/nginx/bin:$PATH

Can I Set Dockerfile ENV via a File?

It seems not.

If you use docker compose, you can group environment variable values into a separate file using an .env file or --env-file. However, this does not seem to be possible with a Dockerfile.

Difference from ARG

  • ENV allows you to embed environment variables into the container generated from the Dockerfile.
  • ARG allows you to set variables that can be used within the Dockerfile.

They look similar, but they are quite different.

Conclusion

I have written other articles related to Dockerfile as well.

I have summarized my knowledge gained from developing at home every day for two and a half years! Please take a look if you'd like.

https://doityourself.jp/articles/2026/full-platform-development/

Discussion