In this post, we will see how to override the connection string of the Web API Docker image, created in the post Docker – Web API and Sql Server
In this project we have two connections strings, defined in appsettings.json:
"AllowedHosts": "*",
"ConnectionStrings": {
"DbConnectionForDocker": "Server=192.168.88.128;Database=TestDocker1;User Id=xx;Password=xxxx",
"DbAzureConnection": "Server=tcp:dockertestapi.database.windows.net,1433;Initial Catalog=dockertest;Persist Security Info=False;User ID=xxxxxx;Password=xxxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
}
and, before we created our Docker image, we have selected the last one in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DataContext>(options => {
options.UseSqlServer(Configuration["ConnectionStrings:DbAzureConnection"]);
});
services.AddScoped<IUserCore, UserCore>();
services.AddScoped<IUnitOfWork, UnitOfWork>();
services.AddScoped<IUserRepository, UserRepository>();
services.AddControllers();
}
Now, if we run this container, using the command docker run -p 80:80 commander2020/webapidocker,
this will be the result:
The application works fine and it uses the Azure SqlServer database.
But, how can we run the application, using for example a database on premises, without modify the Docker images?
We can override the environment variables, using the options -e of the docker run command.
For example, if we want to run another Docker container, using a database called “TestDocker1” that runs in the server 192.168.88.128, we have to execute the command: docker run -p 8088:80 commander2020/webapidocker -e “ConnectionStrings:DbAzureConnection”=”Server=192.168.88.128;Database=TestDocker1;User Id=xx;Password=xxxxx”
Now, if we open a browser and we go to http://localhost:8088/users, this will be the result:
Finally, using the command docker ps –all, we can see the two docker containers running in our system: