Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 69 of 8021. Container FundamentalsFree lesson

Managing Secrets and Sensitive Configuration

Utilize secure secret management tools to inject sensitive environment variables and credentials into containers without hardcoding them in images.

In this lesson, you will learn how to keep your sensitive credentials out of your container images to prevent accidental exposure and security breaches.

When building container images, it is tempting to include files like .env, database passwords, or API keys directly inside the Dockerfile or copy them into the image filesystem. However, this is a major security risk. If you push that image to a registry, anyone with access to the image can easily extract those secrets by inspecting the layers or running docker history. Because container images are meant to be portable and reusable, hardcoding secrets makes them rigid and dangerous.

The "Inject, Don’t Hardcode" Approach

Instead of baking secrets into the image, we treat them as external configuration that is "injected" into the container only when it starts. Think of your container image as a generic template—like a blank application—that receives its unique identity (the secret) through environment variables or files at runtime.

For example, instead of storing a password in your code, you instruct your application to look for an environment variable. When you run your container, you pass the value dynamically:

# Don't do this: 
# ENV DB_PASSWORD=my-secret-password

# Do this instead:
docker run -e DB_PASSWORD=$MY_ACTUAL_PASSWORD my-app-image

By using the -e flag (or similar mechanisms in orchestration tools), the secret exists only in the volatile memory of the running container. It never touches the disk of the image itself, ensuring that your image remains clean and safe to share across your development, staging, and production environments.

In more advanced scenarios, you can use specialized secret management tools or orchestrator-native features (like Kubernetes Secrets) to mount these values as temporary files inside the container’s isolated filesystem. This keeps the credentials encrypted at rest and ensures they are only accessible to the specific process that needs them, upholding the Principle of Least Privilege we discussed earlier.

Key Takeaway: Never embed credentials in your Docker images; always inject them at runtime using environment variables or secure mounting to keep your production secrets safe and isolated.