Is it possible to pass an environment variable to a dockerfile at build time, for instance, in order to install some files during the build that require authentication to fetch.
3 Answers
This method will achieve what you want, but is not recommended for secrets (secrets are hard).
You can use Build Args. The idea is that you place an ARG
instruction in your Dockerfile which is then referenceable within the Dockerfile.
FROM alpine:3.3
ARG some-thing=<optional default value>
You can use this variable later in the Dockerfile like:
...
RUN echo $some-thing
...
Then when you build the image, you can pass the ARG
into docker build
like:
$ docker build --build-arg some-thing=some-value .
This will pass 'some-value' into the Docker build process as the ARG
'some-thing'.
You'd get
echo $some-thing
"some-value"
The values of your ARG
s are not persisted in the end image though. So you don't have to worry about passwords etc leaking into the final image. However Docker still do not recommend it as a way of passing secrets.

- 17,264
- 5
- 48
- 52
-
4The reason it's not recommended for secrets is the commands will end up in the Docker history. – ldg Jul 27 '16 at 10:50
If you run docker build --help
it will tell you what arguments it accepts. If you look through that you will find:
--build-arg=[] Set build-time variables
If you can't work out how to use it, consult the full Docker documentation.

- 57,726
- 6
- 119
- 134
Dockerfile provides Entrypoint to achieve this. You can create a shell script as the entrypoint of your image, and this shell script could take some command as parameters.
Here is an example that I created recently. The entrypoint script will take a SSH key pair as parameters, to clone a private git repository inside of the container.

- 2,672
- 2
- 28
- 32
-
But then all this stuff will be baked in the image? This is not the answer. – johnharris85 Jul 27 '16 at 03:51
-
@JHarris Sorry I don't get your point. Could you let me know the meaning of "all this stuff"? Scripts or parameters or other things? – Haoming Zhang Jul 27 '16 at 04:09
-
OK, so, you're not exactly doing that. I'm not really sure what you're doing. Your image builds another image by doing an intermediate clone. Why wouldn't I just clone on my machine then copy the code in before distributing it? – johnharris85 Jul 27 '16 at 04:27
-
@JHarris Hi, my scripts is a part of another project, so it's hard to explain what I'm doing. I just use it as an example, to show that Dockerfile's Entrypoint could take parameters or environment variables. – Haoming Zhang Jul 27 '16 at 17:29
-
Entrypoint runs in a container, not during the build process for an image. – Ten Bitcomb Nov 22 '17 at 18:33