Published on

Docker Drill

image
Authors
  • avatar
    Name
    David Jimenez
    Twitter

A drill is an exercise aimed at retaining core skills.

This drill consists of running in Docker a system comprised of two components: an ASP.NET Web API app, and a supporting database. This means that we need to run two containers that are able to communicate with each other.

The first step is to create an image for our application:

docker build . -t myapp-image

Then we create a network. We will attach both containers to this network:

docker network create myapp-network

Next, we run a container with the database. In this example we are running MS SQL Server. We give it the hostname of myapp-db-server, though it can be replaced with anything more meaningful:

docker run --network myapp-network --hostname myapp-db-server -e "ACCEPT_EULA=Y" -e "MSSQL_SA_PASSWORD=yourStrong(!)Password" -p 1433:1433 -d mcr.microsoft.com/mssql/server:2022-latest 

Finally, we run the container for our ASP.NET Web API app. We pass two environment variables:

  1. A connection string to the database. Note that in the server specified matches the hostname we assigned to the database container in the previous step.
  2. ASPNETCORE_ENVIRONMENT. In this case we pass the value of Development because we want to see the swagger pages for the API which are configured only for this environment.1
docker run -e "ConnectionStrings__DB=Server=myapp-db-server;Database=myapp-db;Persist Security Info=False;Encrypt=True;TrustServerCertificate=True;Connection Timeout=30;MultipleActiveResultSets=True;User Id=sa;Password=yourStrong(!)Password;" -e "ASPNETCORE_ENVIRONMENT=Development" --network myapp-network -d -p 180:80 -p 1443:443 --name myapp-container myapp-image

We can verify that both containers are in the same network by inspecting the network:

docker network inspect myapp-network
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

Footnotes

  1. This is configured in Program.cs