mark
mark

Reputation: 2073

Pass environment variables to Dockerfile during build time

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.

Upvotes: 5

Views: 11510

Answers (3)

johnharris85
johnharris85

Reputation: 18986

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 ARGs 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.

Upvotes: 4

Graham Dumpleton
Graham Dumpleton

Reputation: 58563

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.

Upvotes: 0

Haoming Zhang
Haoming Zhang

Reputation: 2852

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.

Upvotes: -1

Related Questions