Overwrite Connecting String via Environment Variable for ASP.NET Core on Docker

Kontext Kontext event 2023-04-25 visibility 6,025
more_vert

Containerized application is now commonly used in cloud or on-premise platforms. This article shows you how to overwrite an ASP.NET Core connection string configuration in appsettings.json via environment variables in Docker Linux containers. The same approach can be applied to any other type of configuration property.

Scenario

Assuming the following is the default appsettings.json in your ASP.NET Core web application.

{  
    "ConnectionStrings": {    
        "DefaultConnection": "Server=localhost;Database=kontext;User id=sa;Password=password;MultipleActiveResultSets=true;"  
    }
}


To overwrite this default connection string, we need to use environment variable syntax "SectionName__PropertyName".  For this case, the environment variable should be ConnectionStrings__DefaultConnection.

This approach can be applied to overwrite all other settings in appsettings.json file. 

Run docker

We can pass in environment variable to overwrite the default configuration:

docker run -e ConnectionStrings__DefaultConnection="Server=host,1433;D...;"


Use .env file

To use .env file in docker or docker compose command, simply add the following into the file:

ConnectionStrings__DefaultConnection=Server=host,1433;D...;
OtherSection__Property=Overwrite property...
More from Kontext
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts