简体   繁体   中英

How to override ASP.NET Core connection string with Dockerfile

I'm trying to override the following connection string which is located inside appsettings.json on an ASP.NET Core API.

"ConnectionStrings": {
  "Connection": "Server=localhost\\SQLEXPRESS;Database=NetCoreSample;User Id=sa;Password=sa;MultipleActiveResultSets=true"
  },

To achieve so I added AddEnvironmentVariables() to my HostBuilder :

private static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            config.AddEnvironmentVariables();
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

And my Dockerfile is as follows:

FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build-env

WORKDIR /src
COPY . ./

ENV CONNECTIONSTRINGS__CONNECTION="Server=sql-server;Database=NetCoreSample;User Id=sa;Password=sa@a2020;MultipleActiveResultSets=true" 

WORKDIR /src/Api
RUN dotnet restore 
RUN dotnet publish -c Release -o out --no-restore

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1

COPY --from=build-env /src/Api/out .
ENTRYPOINT ["dotnet", "Api.dll"]

EXPOSE 80

Note that my API and SQLServer are being built on docker-compose .

Yet when I try to run the image, my API throws this error, related to the connection string.

Verify that the instance name is correct and that SQL Server is configured to allow remote connections.

If I override the connection string manually on the .json file it works just fine. So It's clear to me that my ConnectionString is not being properly overridden.

What am I doing wrong here?

You can use different appsetings.json files for every environment. See samples here .

Then you can run your container with required environment name using ASPNETCORE_ENVIRONMENT . For container use this :

docker run -e ASPNETCORE_ENVIRONMENT=environment_name ...

You can see how to set env variables for compose here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM