Search code examples
dockerdocker-build

Docker: Can a secret created and deleted in a single RUN command be recovered from the resulting image?


I want to use some secret keys during my docker building process. So I had the idea to inject these keys as build arguments into the building process. This should be safe. The official documentation states:

Also, these values don’t persist in the intermediate or final images like ENV values do.

Here is an example of a Dockerfile:

FROM ubuntu:latest
ARG key
...
RUN echo $key > /tmp/key && doSomethingWithKey && rm /tmp/key
...

As you can see, at one point I need to paste this key to a file. To make sure this key won't get "baked" into the final image I instantly remove the key.

Here's the build command:

$ docker build --build-arg key="secret" .

Now my question is: Is this safe or does the secret key get "stored" in the final image?


Solution

  • The key won't be stored in the filesystem, but it will be stored in the layer metadata which you can see with a docker history on your image. Therefore I'd recommend against doing this.

    I've seen this request most often with code checkouts from a private repo, where the login to that repo was being used in the build. If that's the case, you should instead checkout the code before the build command and then do a COPY of the checked out code from your Dockerfile.