Containerizing a .NET Web Application with Docker
This is a step-by-step beginner-friendly guide to containerize a .NET web application using Docker. It includes detailed explanations of Docker commands, Dockerfile, and running the container.
✅ Prerequisites
- .NET SDK (v6.0 or later)
- Docker Desktop
- Code editor (like VS Code)
👣 Step-by-Step Instructions
Step 1: Create a New .NET Web Application
dotnet new webapp -n MyWebApp
cd MyWebApp
Step 2: Run the App Locally
dotnet run
Visit https://localhost:5001
in your browser to verify it's working.
Step 3: Create a Dockerfile
Create a file named Dockerfile
in the root directory and paste the following content:
# STEP 1: Build the app
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY . .
RUN dotnet publish -c Release -o /app/publish
# STEP 2: Run the app
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY --from=build /app/publish .
ENTRYPOINT ["dotnet", "MyWebApp.dll"]
Explanation:
- FROM: Specifies the base image.
- WORKDIR: Sets working directory inside the container.
- COPY: Copies files into the container.
- RUN: Executes a command in the container during image build.
- ENTRYPOINT: Command to run when the container starts.
Step 4: Create .dockerignore (Optional)
bin/
obj/
.vscode/
*.md
*.user
Step 5: Build the Docker Image
docker build -t mywebapp .
- build: Tells Docker to build an image.
- -t mywebapp: Tags the image name.
- .: Uses current directory (where Dockerfile is).
Step 6: Run the Docker Container
docker run -d -p 8080:80 --name mywebappcontainer mywebapp
- -d: Runs in detached mode.
- -p 8080:80: Maps local port 8080 to container's port 80.
- --name: Names the container.
Step 7: Manage the Container
Stop the container:
docker stop mywebappcontainer
Remove the container:
docker rm mywebappcontainer
Remove the image:
docker rmi mywebapp
📦 Summary of Docker Commands
Task | Command |
---|---|
Build Docker image |
docker build -t mywebapp .
|
Run container |
docker run -d -p 8080:80 --name mywebappcontainer mywebapp
|
Stop container |
docker stop mywebappcontainer
|
Remove container |
docker rm mywebappcontainer
|
Remove image |
docker rmi mywebapp
|