In this lesson, you will learn how to inject sensitive data like API keys or private tokens into your build process without accidentally baking them into your permanent image layers.
The Problem: Secrets in Layers
When building an image, you might be tempted to use the ENV instruction or copy a file containing a secret to authenticate with a private package registry. If you do this, that secret becomes a permanent part of the image's filesystem. Even if you delete the secret in a later RUN command, it remains captured forever in the previous layer's history. Anyone with access to the image can run docker history and potentially expose your credentials.
The Solution: BuildKit Secrets
Docker BuildKit provides a secure way to mount sensitive information as a temporary file during the RUN instruction. This file exists only in memory while that specific command executes and is never saved to the final image layer.
To use this, you must first enable BuildKit (usually the default in modern Docker versions) and then use the --secret flag.
1. Create your secret file locally:
echo "my-super-secret-token" > token.txt
2. Update your Dockerfile:
Use the --mount=type=secret syntax to access the file:
# syntax=docker/dockerfile:1
FROM alpine
RUN --mount=type=secret,id=my_token \
cat /run/secrets/my_token > /app/config.txt
3. Build the image: Pass the secret during the build process:
docker build --secret id=my_token,src=token.txt .
How it works
When the RUN command executes, BuildKit mounts the token.txt file into the container at /run/secrets/my_token. Your build script can read this file to authenticate with a server, fetch dependencies, or configure your application. Once the RUN instruction finishes, the mount is unmounted and destroyed. The secret is never committed to the image layers, keeping your credentials out of your container registry and version control history.
Key Takeaway: Use --mount=type=secret to securely mount sensitive files into the build process, ensuring credentials remain ephemeral and are never persisted in the final image layers.