Full Byte Developer.

Your .env may be inside the Docker image

If your Dockerfile says COPY . . and there is no .dockerignore, your .env goes into the image.

Published here · 2 sources

If your Dockerfile says COPY . . and there is no .dockerignore in your build folder, your .env goes into the image. Anyone who can pull that image can read it. Push it to a public registry and that means anyone.

Check yours

bash
docker run --rm YOUR_IMAGE sh -c "ls -la"

It starts in your WORKDIR. If .env is in the list, the key is in the image.

Fix 1: a .dockerignore in the root of your build context

text
**/.env
**/.env.*
.git

The **/ also catches .env files in subfolders. A plain .env line only covers the top folder.

Fix 2: build-time secrets never as ARG or ENV

Mount them:

dockerfile
RUN --mount=type=secret,id=aws \
    AWS_SHARED_CREDENTIALS_FILE=/run/secrets/aws \
    aws s3 cp ...
bash
docker build --secret id=aws,src=$HOME/.aws/credentials .

Docker's docs: "Build arguments and environment variables are inappropriate for passing secrets to your build, because they persist in the final image."

After shipping a real key

Rotate it. Deleting the file in a later step does not help: RUN rm /app/.env hid it from the running container, but docker save still showed app/.env with the key in the earlier layer.

Example

Docker 29.8, alpine 3.20, fake key KEY=fake123, image never pushed. Before the .dockerignore, cat /app/.env printed KEY=fake123. After it, "No such file or directory". A build arg API_KEY=fake123 showed up in plain text in docker history.

Ignore before you copy.

Send this to the teammate whose Dockerfile says COPY . . with no .dockerignore.

Keep this guide

By Full Byte Developer

Filed under Dev tools, Security

Questions about this guide

Does deleting the file in a later step help?

No. RUN rm /app/.env hides it from the running container, but docker save still shows app/.env with the key in the earlier layer.

What about build args?

Docker's docs: build arguments and environment variables are inappropriate for passing secrets to your build, because they persist in the final image.

Sources

Next in this stack