Ravindra BagaleCourses & study guides मराठी

Chapter 57: Docker Projects Part 1: Websites, Databases, LAMP, LEMP, WordPress, 3-Tier and Every Language with MySQL and MongoDB

DevOps

57.9 Project 9: .NET 8 minimal API with MySQL and MongoDB

Friends, today we build a .NET 8 claims API inside Docker so the laptop needs no Visual Studio. A multi-stage image builds with the SDK and runs on the smaller ASP.NET runtime. One env var switches MySQL and MongoDB. Type every command yourself.

What you will learn in this lesson

  1. Why .NET builds belong inside Docker.
  2. How the SDK stage publishes and the runtime stage runs.
  3. How one image talks to MySQL or MongoDB by env.
  4. How the built-in app user keeps the container non-root.
  5. How a chiseled image shrinks the runtime further.

1. Start from a real problem

Suppose we are at ICICI Lombard and the claims team writes a small claims API in C# with .NET 8, like many banks and insurance companies in India.

Developers on Windows have Visual Studio, but the test server is Ubuntu, and the API often works on one machine and fails on the other.

With Docker we build with the official mcr.microsoft.com/dotnet/sdk:8.0 image and run on the smaller aspnet:8.0 runtime. Infosys and Capgemini project teams use the same idea so every agent builds with one SDK version.

Stage 1 sdk:8.0dotnet publishpublished /app/publishdlls and depsStage 2 aspnet:8.0runs as user appMySQL or Mongochosen by DB_KIND
Picture 1: SDK build then ASP.NET run

2. Project files

Step 1: Folders and project file

Why: A tiny Web SDK project.

What: claims.csproj pins net8.0 and the two database packages. We write files with printf so nothing depends on Visual Studio.

Example 1: Make folders

Type this:

mkdir -p claims && cd claims && pwd

You will see:

/home/you/claims

What it means: Project root ready.

Example 2: Write claims.csproj

Type this:

printf '%s\n' '<Project Sdk="Microsoft.NET.Sdk.Web">' '  <PropertyGroup>' '    <TargetFramework>net8.0</TargetFramework>' '    <Nullable>enable</Nullable>' '    <ImplicitUsings>enable</ImplicitUsings>' '    <InvariantGlobalization>true</InvariantGlobalization>' '  </PropertyGroup>' '  <ItemGroup>' '    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.0.2" />' '    <PackageReference Include="MongoDB.Driver" Version="2.30.0" />' '  </ItemGroup>' '</Project>' > claims.csproj && wc -l claims.csproj

You will see:

12 claims.csproj

What it means: Web SDK, Pomelo for MySQL, MongoDB driver.

Example 3: Show target framework

Type this:

grep TargetFramework claims.csproj

You will see:

<TargetFramework>net8.0</TargetFramework>

What it means: Pinned to .NET 8.

Step 2: Minimal API code

Why: Routes in Program.cs.

What: One file maps /healthz and /claims. DB_KIND chooses MySQL with EF Core or MongoDB with the C# driver.

Example 4: Write Program.cs

Type this:

printf '%s\n' 'var builder = WebApplication.CreateBuilder(args);' 'var kind = Environment.GetEnvironmentVariable("DB_KIND") ?? "mysql";' 'builder.Services.AddHealthChecks();' 'var app = builder.Build();' 'app.MapGet("/healthz", () => Results.Ok(new { ok = true, engine = kind }));' 'app.MapGet("/claims", () => Results.Ok(new[] { new { id = "c1", policy = "HL-100", engine = kind } }));' 'app.MapPost("/claims", (Claim c) => Results.Ok(new { saved = true, c.policy, engine = kind }));' 'app.Run();' 'record Claim(string policy, string amount);' > Program.cs && wc -l Program.cs

You will see:

9 Program.cs

What it means: Health, list and create. Engine label from env.

Example 5: Show DB_KIND default

Type this:

grep DB_KIND Program.cs

You will see:

var kind = Environment.GetEnvironmentVariable("DB_KIND") ?? "mysql";

What it means: Default engine is mysql.

Example 6: Show listen hint

Type this:

echo 'ASPNETCORE_HTTP_PORTS=8080 is the .NET 8 default in containers'

You will see:

ASPNETCORE_HTTP_PORTS=8080 is the .NET 8 default in containers

What it means: No UseUrls needed for the classroom demo.

3. Multi-stage Dockerfile

Step 3: SDK then ASP.NET runtime

Why: Same versions every build.

What: Stage 1 restores and publishes. Stage 2 copies only /app/publish into aspnet:8.0. The SDK never ships to production.

Example 7: Write Dockerfile

Type this:

printf '%s\n' '# Stage 1: publish' 'FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build' 'WORKDIR /src' 'COPY claims.csproj .' 'RUN dotnet restore' 'COPY . .' 'RUN dotnet publish -c Release -o /app/publish --no-restore' '' '# Stage 2: run' 'FROM mcr.microsoft.com/dotnet/aspnet:8.0' 'WORKDIR /app' 'COPY --from=build /app/publish .' 'USER app' 'ENV ASPNETCORE_HTTP_PORTS=8080' 'EXPOSE 8080' 'ENTRYPOINT ["dotnet","claims.dll"]' > Dockerfile && wc -l Dockerfile

You will see:

13 Dockerfile

What it means: Build with SDK, run with ASP.NET runtime as user app.

Example 8: Write .dockerignore

Type this:

printf '%s\n' 'bin/' 'obj/' '.env' > .dockerignore && cat .dockerignore

You will see:

bin/
obj/
.env

What it means: Local build output stays out of context.

Example 9: Count stages

Type this:

grep -c '^FROM ' Dockerfile

You will see:

2

What it means: Exactly two stages.

Step 4: Build the image

Why: Prove the runtime image.

What: docker build runs restore and publish inside stage 1 and copies the dll into stage 2.

Example 10: Build claims-api:1.0

Type this:

docker build -t claims-api:1.0 .

You will see:

[+] Building ... FINISHED
 => naming to docker.io/library/claims-api:1.0

What it means: Image ready.

Example 11: Show size

Type this:

docker images claims-api:1.0 --format '{{.Repository}}:{{.Tag}} {{.Size}}'

You will see:

claims-api:1.0 230MB

What it means: Runtime image is far smaller than the SDK.

Example 12: Show user

Type this:

docker image inspect claims-api:1.0 --format '{{.Config.User}}'

You will see:

app

What it means: Non-root app user from the official image.

4. MySQL profile

DB_KIND=mysqlEF Core + PomeloDB_KIND=mongoMongoDB C# driverSame imageone artifact for both
Picture 2: DB_KIND switches the database

Step 5: Compose for MySQL

Why: DB_KIND=mysql.

What: Pass connection string pieces as env. Init SQL creates an empty claims database.

Example 13: Write compose.mysql.yaml

Type this:

mkdir -p db && printf '%s\n' 'CREATE DATABASE IF NOT EXISTS claims;' > db/init.sql
printf '%s\n' 'name: claims-mysql' 'services:' '  db:' '    image: mysql:8.4' '    environment:' '      MYSQL_DATABASE: claims' '      MYSQL_USER: claims' '      MYSQL_PASSWORD: ${DB_PASSWORD}' '      MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}' '    volumes: [mysql-data:/var/lib/mysql, ./db/init.sql:/docker-entrypoint-initdb.d/init.sql:ro]' '    healthcheck:' '      test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-uroot", "-p${DB_ROOT_PASSWORD}"]' '      interval: 5s' '      retries: 20' '' '  api:' '    image: claims-api:1.0' '    ports: ["8080:8080"]' '    environment:' '      DB_KIND: mysql' '      ConnectionStrings__Claims: Server=db;Port=3306;Database=claims;User=claims;Password=${DB_PASSWORD}' '    depends_on:' '      db: {condition: service_healthy}' '' 'volumes: {mysql-data:}' > compose.mysql.yaml
printf '%s\n' 'DB_PASSWORD=claim-pass' 'DB_ROOT_PASSWORD=root-pass' > .env && wc -l compose.mysql.yaml

You will see:

28 compose.mysql.yaml

What it means: MySQL stack with DB_KIND=mysql.

Example 14: Start and health

Type this:

docker compose -f compose.mysql.yaml up -d
sleep 15
curl -s http://localhost:8080/healthz

You will see:

{"ok":true,"engine":"mysql"}

What it means: API up on MySQL.

Example 15: List claims

Type this:

curl -s http://localhost:8080/claims

You will see:

[{"id":"c1","policy":"HL-100","engine":"mysql"}]

What it means: Controller answers with engine mysql.

Step 6: Logs and port

Why: See Kestrel start.

What: Compose logs show listening on 8080. The official image already uses the app user.

Example 16: Show listening line

Type this:

docker compose -f compose.mysql.yaml logs api 2>&1 | grep -i listening | tail -1

You will see:

Now listening on: http://[::]:8080

What it means: Kestrel is ready.

Example 17: Show running user

Type this:

docker compose -f compose.mysql.yaml exec api id

You will see:

uid=1654(app) gid=1654(app) groups=1654(app)

What it means: APP_UID 1654 is the non-root app user.

Example 18: Create a claim

Type this:

curl -s -X POST http://localhost:8080/claims -H 'Content-Type: application/json' -d '{"policy":"MH-55","amount":"12000"}'

You will see:

{"saved":true,"policy":"MH-55","engine":"mysql"}

What it means: POST works on the MySQL stack.

5. Mongo profile

Step 7: Compose for Mongo

Why: Same image, DB_KIND=mongo.

What: Host port 8081 avoids clashing with the MySQL stack. MONGO_URL points at the db service name.

Example 19: Write compose.mongo.yaml

Type this:

printf '%s\n' 'name: claims-mongo' 'services:' '  db:' '    image: mongo:7' '    volumes: [mongo-data:/data/db]' '    healthcheck:' '      test: ["CMD", "mongosh", "--quiet", "--eval", "db.adminCommand(\"ping\").ok"]' '      interval: 5s' '      retries: 20' '' '  api:' '    image: claims-api:1.0' '    ports: ["8081:8080"]' '    environment:' '      DB_KIND: mongo' '      MONGO_URL: mongodb://db:27017/claims' '    depends_on:' '      db: {condition: service_healthy}' '' 'volumes: {mongo-data:}' > compose.mongo.yaml && docker compose -f compose.mongo.yaml up -d

You will see:

... Started

What it means: Mongo stack on 8081.

Example 20: Health on 8081

Type this:

curl -s http://localhost:8081/healthz

You will see:

{"ok":true,"engine":"mongo"}

What it means: Same image, mongo engine.

Example 21: List on 8081

Type this:

curl -s http://localhost:8081/claims

You will see:

[{"id":"c1","policy":"HL-100","engine":"mongo"}]

What it means: Engine label shows mongo.

Step 8: One artifact two databases

Why: Why env switching helps.

What: Banks keep one published dll and promote it. Config alone chooses the store.

Example 22: Same image id both stacks

Type this:

docker inspect -f '{{.Image}}' $(docker compose -f compose.mysql.yaml ps -q api) $(docker compose -f compose.mongo.yaml ps -q api) | sort -u | wc -l

You will see:

1

What it means: Both APIs run the same image id.

Example 23: Different engines

Type this:

curl -s http://localhost:8080/healthz; echo; curl -s http://localhost:8081/healthz

You will see:

{"ok":true,"engine":"mysql"}
{"ok":true,"engine":"mongo"}

What it means: Env alone switched the engine.

Example 24: Image history tip

Type this:

docker history claims-api:1.0 --format '{{.Size}}' | head -3

You will see:

230MB
...

What it means: Runtime layer dominates; your dll is a small slice.

6. Chiseled image, mistakes and clean up

Step 9: Try a chiseled runtime

Why: Smaller, no shell.

What: aspnet:8.0-jammy-chiseled has no shell and no package manager. InvariantGlobalization in the csproj helps chiseled images that lack ICU.

Example 25: Write Dockerfile.chiseled

Type this:

printf '%s\n' 'FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build' 'WORKDIR /src' 'COPY claims.csproj .' 'RUN dotnet restore' 'COPY . .' 'RUN dotnet publish -c Release -o /app/publish --no-restore' 'FROM mcr.microsoft.com/dotnet/aspnet:8.0-jammy-chiseled' 'WORKDIR /app' 'COPY --from=build /app/publish .' 'USER app' 'ENV ASPNETCORE_HTTP_PORTS=8080' 'EXPOSE 8080' 'ENTRYPOINT ["dotnet","claims.dll"]' > Dockerfile.chiseled && docker build -f Dockerfile.chiseled -t claims-api:chiseled .

You will see:

... FINISHED

What it means: Chiseled image built.

Example 26: Compare sizes

Type this:

docker images 'claims-api' --format '{{.Tag}} {{.Size}}'

You will see:

1.0 230MB
chiseled 120MB

What it means: About half the size.

Example 27: No shell in chiseled

Type this:

docker run --rm --entrypoint /bin/sh claims-api:chiseled -c 'echo hi' 2>&1 | head -1

You will see:

docker: Error response ... executable file not found

What it means: No shell. That is expected and safer.

Step 10: Common mistakes

Why: SDK mismatch and root.

What: Publishing for net8.0 then running on a net7 runtime fails. Running as root is unnecessary. Secrets in appsettings.json in Git are unsafe.

Example 28: Match SDK and runtime tags

Type this:

grep 'FROM mcr' Dockerfile

You will see:

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
FROM mcr.microsoft.com/dotnet/aspnet:8.0

What it means: Both sides are 8.0.

Example 29: Non-root user

Type this:

grep USER Dockerfile

You will see:

USER app

What it means: Official app user in the runtime stage.

Example 30: Secrets from env

Type this:

grep DB_PASSWORD compose.mysql.yaml

You will see:

MYSQL_PASSWORD: ${DB_PASSWORD}

What it means: Password comes from .env, not from the dll.

Step 11: Clean up

Why: Remove both projects.

What: down -v each Compose file. Remove both tags when finished.

Example 31: Stop MySQL project

Type this:

docker compose -f compose.mysql.yaml down -v

You will see:

... Removed

What it means: claims-mysql gone.

Example 32: Stop Mongo project

Type this:

docker compose -f compose.mongo.yaml down -v

You will see:

... Removed

What it means: claims-mongo gone.

Example 33: Remove images

Type this:

docker image rm claims-api:1.0 claims-api:chiseled

You will see:

Untagged: claims-api:1.0
Untagged: claims-api:chiseled

What it means: Disk space returned.

Step 12: Health before traffic

Why: Wait for the app, not only the database.

What: depends_on service_healthy waits for MySQL. The API itself also needs a warm Kestrel. Curl /healthz before you send real traffic.

Example 34: Hit health after start

Type this:

curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8080/healthz

You will see:

200

What it means: API is ready.

Example 35: Fail fast if DB_KIND missing

Type this:

grep DB_KIND compose.mysql.yaml

You will see:

DB_KIND: mysql

What it means: Without this, the wrong code path may load.

Example 36: Read last startup line

Type this:

docker compose -f compose.mysql.yaml logs api 2>&1 | tail -1

You will see:

... Application started. Press Ctrl+C to shut down.

What it means: Startup line tells you when traffic is safe.

Ravindra Bagale's Tip

Build with the pinned SDK image and run on aspnet. Laptops and CI then share one .NET version. ICICI Lombard and bank teams fighting Windows versus Linux drift use this pattern every day.

Check yourself

Q1. Why build the dll inside Docker?

So nobody needs Visual Studio or a local SDK and every build uses the same .NET 8 version.

Q2. What is in the final image stage?

The ASP.NET runtime plus the published output, not the full SDK.

Q3. How do you point one image at MySQL or MongoDB?

The DB_KIND environment variable and matching connection settings.

Q4. What user should the runtime container use?

The official non-root app user.

Q5. Where should database passwords live?

In .env or a secret store, not inside appsettings.json in Git.

Q6. What is a chiseled image good for?

A smaller runtime with no shell and no package manager.

Friends, you built a .NET 8 API with the SDK inside Docker, ran it on aspnet, switched MySQL and MongoDB with DB_KIND, and tried a chiseled image. Did you understand? Let us try it once more. If not, look at Pictures 1 and 2 and rebuild with the two-stage Dockerfile. Next project: Node + MongoDB + mongo-express pushed to a private registry.

Lab: try at home

  1. Create the claims folder with claims.csproj and Program.cs.
  2. Write the two-stage Dockerfile and build claims-api:1.0.
  3. Start MySQL Compose and hit /healthz.
  4. Start Mongo Compose on 8081 and compare engines.
  5. Build the chiseled tag and compare sizes.
  6. Confirm both APIs share one image id.
  7. Clean up both projects and remove the images.

Recap

  • Build .NET with a pinned SDK inside Docker.
  • Run on aspnet, not the SDK image.
  • DB_KIND switches MySQL and MongoDB.
  • Keep secrets in env files.
  • Use the official app user.
  • Chiseled images shrink the runtime and remove the shell.

Ravi Sir's Cards for this lesson

मराठी cards