我有一个.NET Core api项目,需要在Docker容器中运行。该项目使用NLog将数据记录到数据库中。我想在运行容器时在nlog.config文件中设置连接字符串属性。
该应用程序将部署到不同的客户端,并将使用其数据库进行日志记录。
这是我尝试在nlog.config文件中配置连接字符串的方式:
...
<target name="database" xsi:type="Database">
<connectionString>'${environment:logs_connection_string}'</connectionString>
<dbProvider>MySql.Data.MySqlClient.MySqlConnection, MySql.Data</dbProvider>
...
这是我的Dockerfile:#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
WORKDIR /src
COPY ["Service/Service.csproj", "Service/"]
COPY ["Extensions/CustomExtensions.csproj", "Extensions/"]
RUN dotnet restore "Service/Service.csproj"
COPY . .
WORKDIR "/src/Service"
RUN dotnet build "Service.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "Service.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Service.dll"]
ARG log_connection
ENV logs_connection_string=$log_connection
这些是我在运行时传递连接字符串的一些建议:我在使用Docker方面没有太多经验,因此这种方法甚至不可行。我愿意接受任何建议。
最佳答案
ARG
和ENV
都不适合您要完成的工作。
您需要某种类型的入口点脚本,该脚本将读取您在运行命令中设置的环境变量(示例中为log_connection
或log_connection_string
),如果没有设置,则会发生错误或将其设置为默认值,并最终进行编辑nlog.config
并将<connectionString>
的值设置为变量的值,最后运行dotnet Service.dll
。
例如,您可以像这样在nlog.config
中设置连接对象:
<connectionString>log_connection_string</connectionString>
然后创建内容如下的run.ps1
文件:#!/opt/microsoft/powershell/7/pwsh
if (-not (Test-Path env:log_connection_string)) { $env:log_connection_string = 'default value for log_connection_string' }
((Get-Content -Path path\to\nlog.config -Raw) -replace 'log_connection_string',$Env:log_connection_string) | Set-Content -Path path\to\nlog.config
dotnet Service.dll
在镜像构建期间将其复制到目录/app
并将Dockerfile的最后三行替换为:ENTRYPOINT ["./run.ps1"]
编辑:要在基础镜像中安装Powershell Core,请在Dockerfile中使用以下命令(最好在
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base
下方):RUN curl https://packages.microsoft.com/config/debian/10/packages-microsoft-prod.deb --output packages-microsoft-prod.deb --silent && \
dpkg -i packages-microsoft-prod.deb && \
rm packages-microsoft-prod.deb && \
apt-get update && \
apt-get install -y powershell && \
apt-get clean
您还需要使run.ps1
可执行或将入口点更改为:ENTRYPOINT ["/opt/microsoft/powershell/7/pwsh", "-Command","./run.ps1`enter code here`"]
另外,您可以在Bash中使用等效脚本(我们将其命名为run.sh
):#!/bin/bash
[[ -z "$log_connection_string" ]] && export log_connection_string="default value for log_connection_string"
sed -i 's/log_connection_string/'"$log_connection_string"'/' path\to\nlog.config
dotnet Service.dll
入口点应设置为:ENTRYPOINT ["/bin/bash", "-c", "./run.sh"]
最后说明:没有法律禁止使用小写的名称表示环境变量,但是通常的惯例是用大写字母写成大写,例如。 LOG_CONNECTION_STRING
而不是log_connection_string
。
关于docker - NLog配置从docker run参数设置连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63228745/