Table of Contents

Docker - Security - Don’t leak sensitive information to docker images

It’s easy to accidentally leak secrets, tokens, and keys into images when building them.

To stay safe, follow these guidelines:

Sometimes, when building an application inside a Docker image, you need secrets such as an SSH private key to pull code from a private repository, or you need tokens to install private packages.

If you copy them into the Docker intermediate container they are cached on the layer to which they were added, even if you delete them later on.

These tokens and keys must be kept outside of the Dockerfile.


Using Docker secret commands

Use an alpha feature in Docker for managing secrets to mount sensitive files without caching them, similar to the following:

Dockerfile
# syntax = docker/dockerfile:1.0-experimental
FROM alpine
 
# shows secret from default secret location
RUN --mount=type=secret,id=mysecret cat /run/secrets/mysecre
 
# shows secret from custom secret location
RUN --mount=type=secret,id=mysecret,dst=/foobar cat /foobar

Read more about Docker secrets on their site.


Beware of recursive copy

You should also be mindful when copying files into the image that is being built.

For example, the following command copies the entire build context folder, recursively, to the Docker image, which could end up copying sensitive files as well:

COPY . .

If you have sensitive files in your folder, either remove them or use .dockerignore to ignore them:

private.key
appsettings.json