Reputation: 1275
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?
Upvotes: 1
Views: 5065
Reputation: 706
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.
Upvotes: 1