How to bring credentials into a Docker container during build

roehrijn picture roehrijn · May 31, 2016 · Viewed 13.7k times · Source

I'm wondering whether there are best practices on how to inject credentials into a Docker container during a docker build. In my Dockerfile I need to fetch resources webservers which require basic authentication and I'm thinking about a proper way on how to bring the credentials into the container without hardcoding them.

What about a .netrc file and using it with curl --netrc ...? But what about security? I do no like the idea of having credentials being saved in a source repository together with my Dockerfile.

Is there for example any way to inject credentials using parameters or environment variables?

Any ideas?

Answer

xer0x picture xer0x · Feb 15, 2018

A few new Docker features make this more elegant and secure than it was in the past. The new multi-phase builds let us implement the builder pattern with one Dockerfile. This method puts our credentials into a temporary "builder" container, and then that container builds a fresh container that doesn't hold any secrets.

You have choices for how you get your credentials into your builder container. For example:

  • Use an environment variable: ENV creds=user:pass and curl https://[email protected]
  • Use a build-arg to pass credentials
  • Copy an ssh key into the container: COPY key /root/.ssh/id_rsa
  • Use your operating system's own secure credentials using Credential Helpers

Multi-phase Dockerfile with multiple FROMs:

## Builder
FROM alpine:latest as builder
#
# -- insert credentials here using a method above --
#
RUN apk add --no-cache git
RUN git clone https://github.com/some/website.git /html

## Webserver without credentials
FROM nginx:stable
COPY --from=builder /html /usr/share/nginx/html