In my .net core Api i use secrets.json:
{"UserServiceSecretKey": "secretKey123456"}
Evidently in my .csproj:
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UserSecretsId>6da803bf-439d-4e34-8735-195d652e8366</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
And use in my Startup.cs ConfigureServicesMethod():
var secretKey = Configuration["UserServiceSecretKey"];
if (string.IsNullOrEmpty(secretKey))
Console.WriteLine("Error: KEY UserServiceSecretKey cannot be null...");
If run the application on IISExpres it works (get the secret key).
But if i run the Api in docker like docker-compose, then in runtime the secret key is not obtained:
In my docker-compose.override file i have:
tresfilos.users.service:
environment:
- ASPNETCORE_ENVIRONMENT= Development
- ASPNETCORE_URLS= https://+:443;http://+:80
ports:
- "7002:80"
- "7003:443"
volumes:
- ${APPDATA}/Microsoft/UserSecrets:/root/.microsoft/usersecrets:ro
- ${APPDATA}/ASP.NET/Https:/root/.aspnet/https:ro
Additional, i have defined the APPDATA environment variable:
How can i access to secret key when i run the Api in docker ?
Docker secrets are loaded into memory as files inside /run/secrets
directory, not as mounted directory, so you need to read it from memory
There are 3 steps,
1. docker-compose file
version: "3.9"
services:
redis:
image: redis:latest
deploy:
replicas: 1
secrets:
- my_secret
- my_other_secret
secrets:
my_secret:
file: ./my_secret.txt
my_other_secret:
external: true
note: you can add secrets to docker either by using a file or by defining as external resource, which means that it has already been defined in Docker, either by running the docker secret create command or by another stack deployment. If the external secret does not exist, the stack deployment fails with a secret not found error.
2. Install a nuget package
Microsoft.Extensions.Configuration.KeyPerFile
3. Add a config entry to Startup.cs
config.AddKeyPerFile(directoryPath: "/run/secrets", optional: true);