ASP.NET Core cookbook · Beginner
Publish a container image without a Dockerfile
Maintaining Dockerfiles for many services is repetitive, and images run as root.
Approach
Use the .NET SDK's built-in container publishing: set the image name and base image in the project file and
run dotnet publish /t:PublishContainer. .NET images run as a non-root user by default.
Solution
# Build and push a multi-arch image straight from the SDK
dotnet publish src/Orders.Api -c Release \
-p:ContainerRegistry=registry.example.com \
-p:ContainerRepository=shop/orders-api \
-p:ContainerImageTags='"1.4.0;latest"' \
-p:ContainerRuntimeIdentifiers='"linux-x64;linux-arm64"' \
/t:PublishContainer
Pitfalls
- Pushing
latestonly, so deployments can't be pinned or rolled back. - Forgetting
ASPNETCORE_HTTP_PORTSwhen the platform expects a port other than the default 8080. - Including development appsettings or secrets in the image.
Variations
- Set
<ContainerFamily>noble-chiseled</ContainerFamily>for smaller, shell-less runtime images. - Native AOT (
<PublishAot>true</PublishAot>) withruntime-depsbase images for very small, fast-starting APIs.
Further reading: Containerize a .NET app with dotnet publish
Reference: https://learn.microsoft.com/en-us/dotnet/core/containers/sdk-publish
More ASP.NET Core recipes
- Accept file uploads with size and type limits
- Add OpenTelemetry traces and metrics
- Apply EF Core migrations safely during deployment
- Bind and validate options at startup
- Cache responses with output caching and evict by tag
- Call external APIs with typed HttpClients and resilience
- Configure CORS for a browser front end
- Expose liveness and readiness health checks