How to set kubernetes secret as as connection string password in .NET Core?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
In Kubernetes, the usual pattern is to store only the sensitive part of a database connection, such as the password, in a Secret, then let the .NET application assemble the full connection string at runtime. This keeps credentials out of source control and avoids baking them into container images or plain configuration files.
Create the Secret
You can define a secret with stringData so Kubernetes handles the encoding for you.
Apply it:
That creates a secret with one key named DB_PASSWORD.
Inject the Secret into the Pod
The most common way is an environment variable:
Now the container process can read DB_PASSWORD at runtime.
Build the Connection String in .NET
Modern .NET reads environment variables through the default configuration pipeline, so you can access the secret with builder.Configuration.
Using a connection-string builder is safer than manual string concatenation because it handles formatting and escaping correctly.
Keep Secret and Non-Secret Settings Separate
A practical split is:
- keep host, database name, and username in normal config
- keep only the password in the Kubernetes secret
Example appsettings.json:
Then read those values together with DB_PASSWORD and build the final connection string at startup. This keeps secret rotation and environment configuration easier to manage.
Secret Files Are Another Option
Kubernetes can also mount secrets as files instead of environment variables:
Then the application can read /app/secrets/DB_PASSWORD. This is useful when a library expects file-based secrets or when you prefer not to expose them as environment variables.
Security Notes
Kubernetes secrets are sensitive operational data, but they are not magically secure just because they are called secrets. Access control, cluster configuration, and secret rotation still matter.
Also avoid logging the full connection string. A single debug statement can undo the point of storing the password safely.
Common Pitfalls
One common mistake is storing the entire connection string in the secret even though only the password is sensitive. That makes normal environment configuration harder.
Another issue is building the connection string with raw string concatenation instead of a connection-string builder.
A third pitfall is assuming updated environment-variable secrets appear live in a running process. In many deployments, pods need to be restarted for the change to take effect cleanly.
Summary
- Store the database password in a Kubernetes
Secret. - Inject it into the pod as an environment variable or mounted file.
- Build the final connection string in .NET at runtime.
- Keep non-secret settings in normal application configuration.
- Avoid logging or hard-coding the final credential-bearing connection string.

