I have an asp.net core API 2.2 implemented. I have created a docker image. I would like to override connection strings in appsettings.json file.
Is there any way to do it? I tried via environment variables when I start the container with command docker container run -e "ConnectionStrings:DefaultConnection={...here goes the connection string}"
I have also builder.AddEnvironmentVariables();
in my Startup.cs but connection string in my appsetting.json is not replaced.
I checked it inside the container, appsetting.json is there but the values are not replaced.
Any other way how to do such cases? Thx.
For -e
, it will override the system environment which will change the connectionstring when you retrive from code, it will not affect the content in appsettings.json
.
For example
Assume you have a appsettings.json
like
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-TestDockerConfiguration-416C6FD2-3531-42D6-9EDE-18AC45901208;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
Retrive the connectionstring by _configuration.GetConnectionString("DefaultConnection")
like
public class HomeController : Controller
{
private readonly IConfiguration _configuration;
public HomeController(IConfiguration configuration)
{
_configuration = configuration;
}
public IActionResult Index()
{
return Ok(_configuration.GetConnectionString("DefaultConnection"));
//return View();
}
}
For docker run -it -p 8888:80 dockerconfiguration
, it will return "Server=(localdb)\\mssqllocaldb;Database=aspnet-TestDockerConfiguration-416C6FD2-3531-42D6-9EDE-18AC45901208;Trusted_Connection=True;MultipleActiveResultSets=true"
for Index Action
For docker run -it -p 8888:80 dockerconfiguration -e "ConnectionStrings:DefaultConnection"="testsqlstring"
, it will return testsqlstring
So, if you only want to override the value in appsettings.json
during runtime, you just need to specify like Step 4
If you prefer change the appsettings.json file in docker container, you could follow steps below
vi
command with apt-get install vim -y
docker exec -it 43ea835776dd /bin/bash
to go into container ls
to list files and find the appsettings.json
vi appsettings.json
to modify the contentcat appsettings.json
to check the content whether it is changedexit
and access the Home/Index
to check the result.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With