How to Avoid Leaking Sensitive Information Into Docker Images

DZone 's Guide to

How to Avoid Leaking Sensitive Information Into Docker Images

Learn more about Docker image security.

· Security Zone ·
Free Resource

This tip is part of a complete 10 Docker image security best practices you should adopt. Thanks for reading, and thanks to Omer Levi Hevroni who worked helped me.

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 Multi-Stage Builds

By leveraging Docker support for multi-stage builds, fetch and manage secrets in an intermediate image layer that is later disposed of so that no sensitive data reaches the image build.

Use code to add secrets to said intermediate layer, such as in the following example:

FROM: ubuntu as intermediate

COPY secret/key /tmp/
RUN scp -i /tmp/key build@acme/files .

FROM ubuntu
COPY --from intermediate /app .

Using Docker Secret Commands

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

# 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

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:


The original blog post includes a high-resolution printable PDF like the snippet you see below. Check it out

Image title

docker images ,docker ,containers ,security ,devops ,secrets management

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}