Set up a web app
Create a solution and add a Razor web application. I choose Razor for this example, as it easily demonstrates if everything works as expected.
mkdir HelloDocker cd HelloDocker dotnet new sln --name HelloDocker dotnet new webapp --name HelloDocker.Web dotnet sln add HelloDocker.Web cd HelloDocker.Web dotnet user-secrets init dotnet user-secrets set some_token "token from user secrets" dotnet run .
I now slightly modify the Index page model to retrieve the secret. This could be an authentication token for example. Later I show how to set the secret as an environment variable when running the container, locally and on Azure.
public class IndexModel : PageModel { private readonly IConfiguration _configuration; public IndexModel(IConfiguration configuration) => _configuration = configuration; public string SomeToken => _configuration.GetValue<string>("some_token") ?? string.Empty; }
And the view:
@page @model IndexModel @{ ViewData["Title"] = "Home page"; } <div class="text-center"> <h1 class="display-4">Hello Docker!</h1> <p>Some token: @Model.SomeToken</p> </div>
Build the container
Most of the documentation from this section is from Containerize an app with dotnet publish.
First add the containers build package as a reference to the web project:
First add the containers build package as a reference to the web project:
dotnet add package Microsoft.NET.Build.Containers
Then configure the container properties in HelloDocker.Web.csproj (add the bold properties):
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>net7.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> <UserSecretsId>bf8f7cf6-5186-46b2-bb5b-26b5fbf79806</UserSecretsId> <ContainerImageName>hello-docker</ContainerImageName> <ContainerImageTag>1.0.1</ContainerImageTag> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.NET.Build.Containers" Version="0.3.2" /> </ItemGroup> </Project>
Now build the container. It will be published to Docker Desktop:
dotnet publish --os linux --arch x64 -p:PublishProfile=DefaultContainer -c Release
Run the container locally
Now to run the container locally. Notice that I only pass the token as an environment variable when running the container. That means that I can set a different key for a different environment. I don't need to modify the image.
docker run -dp 8081:80 -e "some_token=secret from docker" hello-docker:1.0.1
Publish the container to Azure
First create an Azure container registry in the Azure portal. Login to the container registry from the Docker command-line:
docker login mycontainerregistry.azurecr.io
Prefix/tag the image with the registry login URI so it can be pushed:
docker tag hello-docker:1.0.1 mycontainerregistry.azurecr.io/hello-docker:1.0.1
And finally push the image to Azure:
docker push mycontainerregistry.azurecr.io/hello-docker:1.0.1