# Publish and Docker — .NET Core: Build, Test and Ship Web APIs

Source: https://www.geekswithgeeks.com/en/dotnet-core/ship-publish-docker

> Publish a release build and package it with a multi-stage Dockerfile.

## Build once, run anywhere

`dotnet publish -c Release` produces the files to deploy. A multi-stage Dockerfile builds with the big SDK image and copies only the output into the small ASP.NET runtime image, which keeps the final image small and free of build tools.

## From laptop to production

You publish a build, package it in a container, run it somewhere, and watch it.

![Four stages: publish, containerize, deploy, observe.](assets/figures/dotnet-core/section-8-map.svg) — Figure 8.1 — Publish, containerize, deploy, observe.

## Multi-stage Dockerfile

Replace `Shop.Api` with your project name. Recent .NET images run as a non-root user and listen on port 8080.

```dockerfile
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY . .
RUN dotnet publish src/Shop.Api -c Release -o /app

FROM mcr.microsoft.com/dotnet/aspnet:10.0
WORKDIR /app
COPY --from=build /app .
EXPOSE 8080
ENTRYPOINT ["dotnet", "Shop.Api.dll"]
```

## Add a .dockerignore

Exclude `bin/`, `obj/`, `.git/` and local secrets from the build context. It speeds up builds and prevents accidentally baking a secret into an image layer.

**Quiz:** Why use a multi-stage Dockerfile?

- [x] The final image contains only what is needed to run
- [ ] It makes C# run faster
- [ ] Docker requires exactly two stages
- [ ] It removes the need to publish

*Answer:* The final image contains only what is needed to run. The SDK stays in the build stage; only the compiled output ships in the smaller runtime image.
