DEV Community

Matthew LaFalce
Matthew LaFalce

Posted on

Securely Accessing Private Resources in Docker Builds with BuildKit

Accessing private repositories and services in Docker builds has always been a challenge. Traditional methods, such as environment variables or secret files, pose security risks since they remain in image metadata or cache. While multi-stage builds offer some mitigation, they require careful handling.

Docker 18.09 introduced a new backend, BuildKit, which provides a secure and efficient way to manage secrets in Docker builds.

Enabling BuildKit

To enable BuildKit, set the following environment variable before running docker build:

export DOCKER_BUILDKIT=1
Enter fullscreen mode Exit fullscreen mode

Using Build Secrets

BuildKit introduces --mount=type=secret, allowing secrets to be securely used in RUN commands without persisting them in the final image.

Defining a Secret in a Dockerfile

RUN --mount=type=secret,id=mysite.key command-to-run
Enter fullscreen mode Exit fullscreen mode

This makes the secret available at /run/secrets/mysite.key during the RUN step.

Passing Secrets During Build

docker build --secret id=mysite.key,src=path/to/mysite.key .
Enter fullscreen mode Exit fullscreen mode

You can specify multiple secrets, and use the required flag to ensure a build fails if a secret is missing:

RUN --mount=type=secret,id=mysite.key,required <command-to-run>
Enter fullscreen mode Exit fullscreen mode

Secure SSH Access

For private repositories, BuildKit allows SSH forwarding without exposing private keys.

Using SSH in a Dockerfile

# syntax=docker/dockerfile:experimental
FROM alpine
RUN apk add --no-cache openssh-client git
RUN mkdir -p -m 0600 ~/.ssh && ssh-keyscan github.com >> ~/.ssh/known_hosts
RUN --mount=type=ssh git clone git@github.com:myorg/myproject.git myproject
Enter fullscreen mode Exit fullscreen mode

Enabling SSH Forwarding

docker build --ssh default .
Enter fullscreen mode Exit fullscreen mode

Instead of passing private keys, Docker forwards the SSH agent connection. You can define specific keys per repository:

docker build --ssh projecta=./projecta.pem --ssh projectb=./projectb.pem
Enter fullscreen mode Exit fullscreen mode

Conclusion

With BuildKit, Docker provides a secure, ephemeral, and cache-safe way to manage secrets and SSH access in builds. By leveraging these features, developers can confidently handle private resources without compromising security.

Top comments (0)