Dr *_*car 4 environment-variables docker docker-compose asp.net-core docker-secrets
在我的 .net core Api 中,我使用 Secrets.json:
{"UserServiceSecretKey": "secretKey123456"}
Run Code Online (Sandbox Code Playgroud)
显然在我的 .csproj 中:
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UserSecretsId>6da803bf-439d-4e34-8735-195d652e8366</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
Run Code Online (Sandbox Code Playgroud)
并在我的 Startup.cs ConfigureServicesMethod() 中使用:
var secretKey = Configuration["UserServiceSecretKey"];
if (string.IsNullOrEmpty(secretKey))
Console.WriteLine("Error: KEY UserServiceSecretKey cannot be null...");
Run Code Online (Sandbox Code Playgroud)
如果在 IISExpres 上运行该应用程序,它就可以工作(获取密钥)。
但是如果我像 docker-compose 这样在 docker 中运行 Api,那么在运行时将无法获得密钥:

在我的docker-compose.override文件中,我有:
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
Run Code Online (Sandbox Code Playgroud)
另外,我定义了 APPDATA 环境变量:
当我在 docker 中运行 Api 时如何访问密钥?
Docker 机密作为目录中的文件加载到内存中/run/secrets,而不是作为安装目录,因此您需要从内存中读取它
有3个步骤,
1.docker-compose文件
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
Run Code Online (Sandbox Code Playgroud)
注意:您可以通过使用文件或定义为外部资源来将机密添加到 docker,这意味着它已经在 Docker 中定义,可以通过运行 docker Secret create 命令或通过另一个堆栈部署来定义。如果外部密钥不存在,堆栈部署将失败并出现密钥未找到错误。
2.安装nuget包
Microsoft.Extensions.Configuration.KeyPerFile
3. 在Startup.cs中添加配置条目
config.AddKeyPerFile(directoryPath: "/run/secrets", optional: true);
| 归档时间: |
|
| 查看次数: |
4037 次 |
| 最近记录: |