runtime: usersecrets are not accessible inside container for worker service project
Describe the bug
The user secrets for a worker service are not accessible inside docker container.
To Reproduce
Steps to reproduce the behavior:
- Create a new .NET Core 3.0/3.1 WorkerService project using Visual Studio. (Or just clone this repo and jump to step 5)
- Right click on the project, click “Add Docker Support” select “Linux”.
- Edit the project file and add -
a. Package reference to
Microsoft.Extensions.Configuration.UserSecretsas following<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="3.1.1" />Because of this issue #2743 b. A volume mapping of the user secrets directory inside the container by adding following line to the property group -<DockerfileRunArguments>-v "$(AppData)/Microsoft/UserSecrets:/root/.microsoft/usersecrets:ro"</DockerfileRunArguments> - Modify the file
Worker.csto access the user secrets -
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private readonly IConfiguration configuration;
public Worker(ILogger<Worker> logger, IConfiguration configuration)
{
_logger = logger;
this.configuration = configuration;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("The secret - {}", this.configuration["secretKey"]);
await Task.Delay(1000, stoppingToken);
}
}
}
-
On powershell or command prompt, navigate to the project directory and add user secrets using the command -
dotnet user-secrets set "secretKey" "secretValue" -
hit F5 with the Docker debug profile and monitor the output window. Notice that the value of the user secret is null.
Note: You can open the Containers window in the VS to check the file contents of the container.
If you check the path - /root/.microsoft/usersecrets you will notice the user-secrets directory with secrets.json inside it.
Expected behavior
The output should print the value of the user-secret.
Screenshots


Additional context
Same program with WorkerService debug profile works well.
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Reactions: 4
- Comments: 15 (7 by maintainers)
There’s no issue with the mount. The docker image default
DOTNET_ENVIRONMENTvalue is * (it’s actually unset). If you set it to Development in thelaunchSettings.json, it will work.