Secrets management in .NET and Docker: keeping passwords out of code, images and logs
A developer joins a project, clones the repository, opens appsettings.Development.json and finds the test database password, an API key for an email service and a payment provider key that was added "temporarily". All of them have been there for months. Nobody had bad intentions; a decision about where secrets should live was simply never made.
Secrets management is often discussed as a choice of tools, but the real issue is discipline: which paths does a password travel through, and where does it leave a trace along each of them? In this post I go through those paths one by one for .NET applications and services packaged with Docker: source code, the development environment, the image build, runtime and logs.
Tracing a secret: where it leaks
The places where secrets leak are usually not the places you expect. The best known is a commit to the repository, but deleting it is not enough, because Git history keeps the value. The day the repository is shared with another team or accidentally made public, every commit in its history is exposed as well.
There are less obvious paths too. Docker image layers can retain values used during the build. Environment variables can be dumped in full on an error page or a diagnostics endpoint. A line that logs the configuration object "just to check" carries the connection string into the logging system, and from there to everyone who can read the logs. CI output, error reporting services and screen sharing carry the same risk.
So the first step is an inventory: for every secret the application uses, answer where it is defined, how it reaches the application and who can read it. That list settles most of the later decisions on its own.
Thinking of .NET configuration in layers
ASP.NET Core's configuration system already offers a good structure for separating secrets. In the default setup, values are read from several sources, and each later source overrides the earlier ones: appsettings.json, the environment-specific appsettings.{Environment}.json, user secrets in development, environment variables and command-line arguments.
The practical rule that follows from this order: appsettings.json carries only the structure and non-secret defaults. Secret fields are either absent or left empty; the real value comes from a later layer.
{
"ConnectionStrings": {
"Default": ""
},
"Smtp": {
"Host": "smtp.example.com",
"Port": 587,
"Password": ""
}
}
In environment variables, nested keys are written with a double underscore: Smtp__Password shows up in configuration as Smtp:Password. This lets the value be injected by the deployment environment without changing anything in the code.
For the development environment, dotnet user-secrets keeps secrets outside the project folder, in the user profile:
dotnet user-secrets init
dotnet user-secrets set "ConnectionStrings:Default" "Host=localhost;Database=app;Username=app;Password=dev-only"
User secrets are not encrypted; their purpose is not to make the secret safe but to keep it out of the repository. The distinction matters: values on a developer machine should still be development-only values with limited privileges.
Catching a missing secret at startup
Moving secrets out of the code has a side effect: when a value is missing, the application still starts, and the error only appears when the first email is sent, perhaps hours later. The way to prevent this is to give the configuration a type and validate it at startup.
public sealed class SmtpOptions
{
[Required] public string Host { get; init; } = "";
[Range(1, 65535)] public int Port { get; init; }
[Required] public string Password { get; init; } = "";
}
builder.Services
.AddOptions<SmtpOptions>()
.Bind(builder.Configuration.GetSection("Smtp"))
.ValidateDataAnnotations()
.ValidateOnStart();
With ValidateOnStart, a missing or invalid value stops the application with a clear error message before it receives any traffic. In a container environment, that means the deployment is marked unhealthy and the old version keeps running. That is a far better outcome than a silent runtime failure.
Make sure error messages contain only the key name, not the value itself. "Smtp:Password must not be empty" is enough; adding the current value to the validation error creates a new leak while fixing the problem.
Not baking secrets into the Docker image
On the Docker side, the most common mistake is passing a secret needed during the build via ARG or ENV. If a private NuGet feed requires an access token, for example, passing it as a build argument looks easy. But values defined with ENV become part of the image and are visible to anyone who pulls it, and ARG values can leave traces in the image history. Deleting the file in a later layer is no fix either, because the earlier layer is still inside the image.
BuildKit's secret mount feature is designed for exactly this. The secret is mounted as a file only for the duration of the relevant RUN step and is never written to a layer:
# syntax=docker/dockerfile:1
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
WORKDIR /src
COPY . .
RUN --mount=type=secret,id=nuget_token \
NUGET_TOKEN="$(cat /run/secrets/nuget_token)" \
dotnet restore && dotnet publish -c Release --no-restore -o /app
docker build --secret id=nuget_token,env=NUGET_TOKEN -t myapp .
A multi-stage build adds a second safeguard: the final image contains only the published output, and files from the SDK stage are not carried over. On top of that, adding .env, *.pfx and local configuration files to .dockerignore keeps the COPY . . line from pulling them into the build context.
Providing secrets as files at runtime
Passing a secret as an environment variable at runtime is common and sufficient in most cases. However, environment variables are inherited by child processes, appear in docker inspect output and are easily dumped by diagnostic tools. A stricter alternative is to mount the secret as a read-only file.
Docker Compose supports this directly; a declared secret appears inside the container as a file at /run/secrets/<name>:
services:
api:
image: myapp
secrets:
- smtp_password
secrets:
smtp_password:
file: ./secrets/smtp_password.txt
On the .NET side, the key-per-file provider can bind these files into configuration. It reads each file name in the directory as a key and its content as the value; a double underscore in the file name again becomes the : separator:
builder.Configuration.AddKeyPerFile("/run/secrets", optional: true);
When you mount the file under the name Smtp__Password, SmtpOptions.Password receives the value without any code changes. In cloud environments, a vault service and its configuration provider play the same role; what matters is that the application does not need to know where the secret comes from.
Protecting secrets in logs and error output
Even after a secret reaches the application safely, it can still leak. The most common way is logging an entire object. A line like logger.LogInformation("Settings: {@Options}", options) looks harmless while debugging, but it carries the password everywhere as a structured log.
A few simple habits reduce this risk considerably. Don't log options classes; if needed, explicitly select only the non-secret fields. Don't include the connection string in error messages. Verify that the developer exception page and any diagnostics endpoints that list environment variables are disabled in production. Make sure the Authorization header is masked in HTTP client logs.
Adding an automated check on the repository side is also a good safeguard: a secret scanning step that runs before commit or in CI can catch high-entropy strings and known key formats. Such scanning is not perfect, but it stops the most common mistake at the cheapest point.
Planning secret rotation from the start
When you discover that a secret has leaked, the first thing to do is invalidate it and issue a new one. Whether this takes minutes or days depends largely on design decisions made up front.
The most important decision that makes rotation easy is supporting two valid values at the same time. In service-to-service signing, for example, verifying with both the old and the new key while signing only with the new one allows the switch without downtime. For database users, you can similarly create a second user, change the connection string and then disable the old one.
Rotating regularly, even without a leak, shows that the process actually works. A procedure that has never been tried is usually one that turns out to be missing a step at the moment you need it.
Secrets management is not a problem solved by a single tool; it is solved by asking the same question at every point the value passes through: who can see this value here, and do they need to? Layering configuration, catching missing values at startup, baking nothing into the image, providing secrets as files at runtime and protecting logs are concrete ways of answering that question at each layer. Once these are in place, leaks become less likely, and when one does happen, the response is a procedure rather than a panic.