Learn ASP.NET Core Β· 13/13

Deployment and Containerization

6 min read

1. Getting Ready for Production: Publishing Your ASP.NET Core App

Definition:
Publishing is the process of packaging your application and its dependencies into a folder structure that is ready to run on a specific server or environment.

The Problem:
When you write code, your files are scattered across project folders (.cs, .csproj, .json). You also rely on the .NET SDK (Software Development Kit) to run the app using dotnet run. However, production servers often don't have the full SDK installed (to save space and improve security), and they need a single, optimized folder to execute the application.

The Solution:
The dotnet publish command compiles your application, reads your dependencies from NuGet, and copies everything into a publish directory. It optimizes the code (Release mode) and removes development-time tools.

πŸ“ Key Concepts

  • Release vs. Debug: Debug includes extra information for fixing bugs but is slower. Release optimizes code for speed and size.
  • Framework-dependent (Default): The app relies on the server having the .NET Runtime installed. Small file size.
  • Self-contained: The app includes the entire .NET Runtime. Larger file size, but runs on a machine without .NET installed.

πŸ› οΈ Hands-on: Publishing an App

Open your terminal in the project root folder.

bash
# The standard command for production
dotnet publish -c Release

What just happened?

  1. -c Release: Tells the compiler to optimize for performance.
    • Note: In .NET 8+, dotnet publish defaults to Release configuration, but being explicit is a good habit!
  2. Output: You will find your files in bin/Release/net8.0/publish/. This folder contains the .dll (Dynamic Link Library) file and appsettings.json.

Did you know? πŸ’‘
You can compile your C# app into a single file executable, just like a Go or Rust app!

bash
dotnet publish -c Release -r linux-x64 --self-contained -p:PublishSingleFile=true

This produces one standalone binary you can just drop onto a Linux server and run.


2. Cloud Hosting: Deploying to Azure App Service

Definition:
Azure App Service is a Platform as a Service (PaaS) offering from Microsoft. It creates a web server for you so you don't have to manage the operating system or security patches manually.

The Problem:
Buying a Virtual Machine (VM) means you have to install Windows/Linux, configure the firewall, install .NET, manage updates, and handle restarts. This is time-consuming and prone to human error.

The Solution:
You hand your code to Azure App Service. Azure handles the OS, load balancing, and scaling. You just focus on the C#.

πŸ“ Key Concepts

  1. Resource Group: A logical container (folder) in Azure to group related resources (e.g., database + web app).
  2. App Service Plan: The "hardware" rental agreement. It defines the region (e.g., East US) and size (e.g., Free Tier, Premium).
  3. Web App: The actual application running on that plan.

πŸ› οΈ Hands-on: Deploying via CLI

While you can use Visual Studio's "Right Click -> Publish", using the CLI is more professional and repeatable.

Prerequisites: Install the Azure CLI.

  1. Login to Azure:

    bash
    az login
  2. The "Magic" Command:
    Run this in your project folder. It creates the Resource Group, Plan, and App all at once.

    bash
    az webapp up --name <your-unique-app-name> --sku F1 --os-type Linux

Breakdown:

  • --name: The URL will be your-unique-app-name.azurewebsites.net.
  • --sku F1: "Free Tier 1". Good for testing, costs $0.
  • --os-type Linux: ASP.NET Core runs great on Linux (often cheaper/faster than Windows).

Interesting Fact πŸ€“
The first time you deploy, it might take a minute. Subsequent deployments only copy the changed files, making it much faster. This is called "Kudu Sync".


3. Shipping in a Box: Containerizing Your App with Docker

Definition:
Containerization bundles your application code and the specific version of the operating system libraries it needs into a lightweight "image".

The Problem:
"It works on my machine!" Β―\(ツ)/Β―
Your local computer might have .NET 8.0.2 installed, but the server has 8.0.1. Or your Mac paths differ from Linux paths. These inconsistencies cause production crashes.

The Solution:
Docker creates an isolated environment (container). If the container runs on your machine, it is guaranteed to run exactly the same way on any server, cloud, or developer's laptop.

πŸ“ Key Concepts

  • Dockerfile: A recipe text file that tells Docker how to build your app.
  • Image: The read-only template created from the Dockerfile (like a CD-ROM).
  • Container: A running instance of an image (like the music playing from the CD).

πŸ› οΈ Hands-on: Creating a Dockerfile

Create a file named Dockerfile (no extension) in your project root.

Standard .NET 8 Multi-Stage Build:

dockerfile
# Stage 1: Build the app
# Use the SDK image (contains compilers, tools - Heavy)
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src

# Copy csproj and restore dependencies (Optimizes caching)
COPY ["MyApp.csproj", "./"]
RUN dotnet restore

# Copy the rest of the code and publish
COPY . .
RUN dotnet publish -c Release -o /app/publish

# Stage 2: Run the app
# Use the ASP.NET Runtime image (Run only - Light)
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS runtime
WORKDIR /app
COPY --from=build /app/publish .

# ⚠️ IMPORTANT: .NET 8+ containers default to port 8080 (not 80!)
EXPOSE 8080
ENV ASPNETCORE_HTTP_PORTS=8080

ENTRYPOINT ["dotnet", "MyApp.dll"]

Commands to run locally:

bash
# 1. Bake the cake (Build image)
docker build -t my-aspnet-app .

# 2. Eat the cake (Run container)
# Map computer's port 5000 to container's port 8080
docker run -p 5000:8080 my-aspnet-app

Now visit http://localhost:5000.

Breaking Change Alert! 🚨
If you are reading older tutorials, they might tell you to expose Port 80. In .NET 8, Microsoft changed the default container port to 8080 to allow containers to run as a non-root user easily (better security). Always check your ports!


4. Basic DevOps: Setting up a CI/CD Pipeline with GitHub Actions

Definition:
CI (Continuous Integration): Automatically build and test code whenever you save (commit).
CD (Continuous Deployment): Automatically release that code to the server if tests pass.

The Problem:
Manually running dotnet publish and dragging files to a server via FTP is risky. What if you forget a file? What if you break the site on a Friday night?

The Solution:
GitHub Actions listens for changes in your repository. When you push code, it spins up a temporary server, builds your app, runs tests, and deploys it for you.

πŸ› οΈ Hands-on: Your First Workflow

  1. Create a folder .github/workflows in your repository.
  2. Create a file named dotnet-publish.yml.
yaml
name: Build and Deploy

on:
  push:
    branches: [ "main" ] # Runs when code hits main branch

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
    # 1. Get the code
    - uses: actions/checkout@v4

    # 2. Setup .NET 8
    - name: Setup .NET
      uses: actions/setup-dotnet@v4
      with:
        dotnet-version: 8.0.x

    # 3. Restore dependencies
    - name: Restore
      run: dotnet restore

    # 4. Build and Test
    - name: Build
      run: dotnet build --no-restore
    
    - name: Test
      run: dotnet test --no-build --verbosity normal

    # 5. Publish (Only if tests pass!)
    - name: Publish
      run: dotnet publish -c Release -o ./publish

    # (Optional) Step 6: Deploy to Azure
    # Requires setting up a publish profile secret in GitHub Repo Settings
    # - name: Deploy to Azure Web App
    #   uses: azure/webapps-deploy@v2
    #   with:
    #     app-name: 'your-unique-app-name'
    #     publish-profile: ${{ secrets.AZURE_WEBAPP_PUBLISH_PROFILE }}
    #     package: ./publish

Why is this cool?
You have now created a "Pipeline". If you make a spelling mistake in your C# code that causes a build error, GitHub will email you saying "Build Failed" and it won't deploy to production. You are safe! πŸ›‘οΈ


πŸ“š References & Further Reading

Challenge

Dockerfile for ASP.NET Core 8 Application

You are tasked with creating a multi-stage Dockerfile to containerize an ASP.NET Core 8 application. The project file is named WebApp.csproj and the final assembly will be WebApp.dll.

Your Dockerfile must meet the following requirements:

Build Stage (named build):

  1. Start from the official .NET 8 SDK image: mcr.microsoft.com/dotnet/sdk:8.0.
  2. Set the working directory to /src.
  3. Copy only the WebApp.csproj file into the container.
  4. Execute dotnet restore for the project.
  5. Copy the rest of the application's source code from the host to the container.
  6. Execute the dotnet publish command to build the application. It must be configured for Release mode, produce a framework-dependent deployment, and place the output in the /app/publish directory.

Final Stage:

  1. Start from the official ASP.NET Core 8 runtime image: mcr.microsoft.com/dotnet/aspnet:8.0.
  2. Set the working directory to /app.
  3. Copy the published application files from the /app/publish directory of the build stage into the current working directory of the final stage.
  4. Set the ASPNETCORE_HTTP_PORTS environment variable to 8080 to align with modern .NET container security defaults.
  5. Expose port 8080.
  6. Define the ENTRYPOINT to execute the application using dotnet WebApp.dll.

Expected result

Your Dockerfile should correctly implement a multi-stage build to create a small, optimized production image for the ASP.NET Core application.

dockerfile
# Stage 1: Build the application

# Use the .NET 8 SDK as a base image and name this stage 'build'
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build

# Set the working directory inside the container
WORKDIR /src

# Copy the project file and restore dependencies
COPY ["WebApp.csproj", "."]
RUN dotnet restore "WebApp.csproj"

# Copy the remaining source code
COPY . .

# Publish the application for release. Output to /app/publish
RUN dotnet publish "WebApp.csproj" -c Release -o /app/publish --no-self-contained


# Stage 2: Create the final runtime image

# Use the ASP.NET Core runtime image as the base
FROM mcr.microsoft.com/dotnet/aspnet:8.0

# Set the working directory
WORKDIR /app

# Copy the published output from the build stage
COPY --from=build /app/publish .

# Set the environment variable for the port
ENV ASPNETCORE_HTTP_PORTS=8080

# Expose the port
EXPOSE 8080

# Set the entry point for the container
ENTRYPOINT ["dotnet", "WebApp.dll"]

Key Concepts Demonstrated:

  • Multi-stage Build: Using FROM ... AS build and COPY --from=build ensures that the final image only contains the lightweight ASP.NET runtime and the published application, not the entire .NET SDK, resulting in a much smaller and more secure image.
  • Layer Caching: Copying the .csproj file and running dotnet restore first allows Docker to cache this layer. The restore step will only be re-run if the project dependencies change, speeding up subsequent builds.
  • Framework-Dependent Deployment: The --no-self-contained flag creates an application that relies on the .NET runtime present in the base image, which is the purpose of using the aspnet image.
  • .NET 8 Port Configuration: Correctly setting ENV ASPNETCORE_HTTP_PORTS and using EXPOSE for port 8080 is crucial for applications built with .NET 8 container images.
dockerfile

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.