Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 150 of 8022. Docker Image LifecycleFree lesson

Managing Secrets Without Hardcoding Credentials

Use build-time arguments and runtime secret injection techniques to prevent sensitive tokens or passwords from being persisted in your image layers.

In this lesson, you will learn how to keep your sensitive credentials out of your Docker images to ensure they never accidentally leak into your container registries or source control.

The Problem: Layer Persistence

When you hardcode a password or API key directly into a Dockerfile—even if you use an ENV instruction—that secret becomes a permanent part of the image's history. Anyone with access to the image can run docker history to see the layer that contained that secret, even if you delete the line in a later commit.

Build-Time vs. Runtime Secrets

To keep your secrets safe, we separate them into two distinct phases:

1. Build-Time Arguments (ARG) If you need a secret only during the build (like a private package registry token to download dependencies), use --build-arg. These variables exist only during the build process and do not persist in the final image layers.

# Use ARG to accept the secret during 'docker build'
ARG GITHUB_TOKEN
RUN git clone https://$GITHUB_TOKEN@github.com/my-private-repo.git

Note: Run your build using docker build --build-arg GITHUB_TOKEN=your_secret_here .

2. Runtime Secret Injection For secrets your application needs to actually run (like database passwords), never put them in the Dockerfile at all. Instead, inject them when the container starts. In a local Docker environment, you might pass these as environment variables, but in Kubernetes, you should use Kubernetes Secrets.

By mounting a Secret object as a file or environment variable, the password is injected into the container's memory at runtime. The Docker image itself remains generic and "clean," containing no sensitive information, allowing you to deploy the same image safely across development, staging, and production environments.

Why this matters

By treating your images as "code only" and your secrets as "configuration injected at runtime," you eliminate the risk of committing a production database password to GitHub or exposing it in a public container registry.

Key Takeaway: Never store credentials in your Dockerfile; use build arguments for temporary build tasks and runtime injection for application credentials to keep your images secure and portable.