当我在容器中运行 SQL Server 以在从本地主机运行时将 API 连接到它时,我需要一种连接字符串。但是,当我使用 Docker Compose 在 Docker 中运行 SQL Server 和 API 时,我需要不同类型的连接字符串。
这是我的 Docker-compose.yaml
version: '3.9'
volumes:
SqlDataStorage:
networks:
my-network:
driver: bridge
services:
weather.api:
container_name: WeatherForecastApi
image: maks0s/weather-app:6.1.0
build:
context: .
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_HTTP_PORTS=8080
- ASPNETCORE_HTTPS_PORTS=8081
- ASPNETCORE_Kestrel__Certificates__Default__Password=********
- ASPNETCORE_Kestrel__Certificates__Default__Path=/https/aspnetapp.pfx
ports:
- '5000:8080'
- '5001:8081'
volumes:
- ~/.aspnet/https:/https:ro
networks:
- my-network
depends_on:
- weather.db
weather.db:
container_name: WeatherForecastCloudDb
image: mcr.microsoft.com/mssql/server:2022-latest
env_file:
- sqlconfig.env
- sapassword.env
ports:
- '1439:1433'
volumes:
- SqlDataStorage:/var/opt/mssql
networks:
- my-network
在容器中运行 SQL Server,为了在从本地主机运行时将我的 API 连接到它,我需要以下类型的连接字符串:
"Data Source=host.docker.internal,1439;Initial Catalog=WeatheForecastDb;User ID=sa;Password=**********; Trust Server Certificate=True; MultiSubnetFailover=True"
但是,当我使用 Docker Compose 在 Docker 中运行 SQL Server 和 API 时,连接字符串应该是:
"Data Source=weather.db;Initial Catalog=WeatheForecastDb;User ID=sa;Password=**********; Trust Server Certificate=True; MultiSubnetFailover=True"
问题来了,是否可以创建一些统一的连接字符串,还是需要使用带有环境变量检查的三元运算符在启动时直接在本地/容器中形成连接字符串?
问题来了,是否可以创建一些统一的连接字符串,还是需要使用带有环境变量检查的三元运算符在启动时直接在本地/容器中形成连接字符串?
理论上,如果您在默认网络中运行所有内容(即从组合中删除
networks:
),您应该能够在两种情况下使用weather.db
(如果您可以使用相同的容器),但“正确”答案是使用 配置 来提供连接字符串。
在配置中添加一些密钥(通常是
ConnectionStrings:SomeDbIdentifier
),然后对于本地环境添加到appsettings.Development.json
:
"ConnectionStrings": {
"SomeDbIdentifier": "Data Source=..."
},
在compose中添加环境变量:
- ConnectionStrings__SomeDbIdentifier=Data Source=weather.db;...
在应用程序中:
// get the configuration depending on the app and the setup
Configuration.GetConnectionString("SomeDbIdentifier");
另请参阅: