LESSON 20 OF 20

20. Production Deployment, Docker, CI/CD, and the Live Application Checklist

This lesson explains how to prepare an ASP.NET Core MVC application for production, package it with Docker, manage migrations and secrets securely, configure CI/CD, and verify the live system after deployment.

45 dk 35

Introduction

This lesson moves our ASP.NET Core MVC content management application from development into a secure and repeatable production process. Earlier lessons established a testable architecture and application tests. A working application on a developer machine is not enough; the application must also be configured, observable, recoverable, and maintainable after release.

We will divide deployment into four areas: preparing production settings, packaging the application as a Docker image, applying database migrations in a controlled way, and automating the process with CI/CD. At the end, we will create a practical checklist for verifying the live application.

1. Separate Development and Production environments

ASP.NET Core applications can run in environments such as Development, Staging, and Production. Production should not expose detailed exception pages, developer-specific settings, or secrets stored in source code. If no environment variable is specified, ASP.NET Core uses the Production environment by default.

You can place general production settings in appsettings.Production.json, but do not put passwords, connection strings with credentials, or API keys in that file. It should contain only non-sensitive settings:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "example.com"
}

In Program.cs, configure production-friendly error handling and HTTPS:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();
builder.Services.AddHealthChecks();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.MapHealthChecks("/health");
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

The principle is simple: development may provide detailed diagnostics, while production should show a safe error page to users. A health endpoint can also be consumed by a load balancer or monitoring service.

2. Manage secrets securely

During development, use Secret Manager for convenience. In production, use the platform's secret store, protected environment settings, or a dedicated key vault. Secret Manager is useful for local development, but it should not be treated as a production-grade secret vault by itself.

Instead of storing a database password in appsettings.json, define the following setting on the production host:

ConnectionStrings__DefaultConnection=Server=sql;Database=ContentDb;User Id=appuser;Password=strong-password;TrustServerCertificate=True

ASP.NET Core uses a double underscore for hierarchical keys in environment variables. ConnectionStrings__DefaultConnection maps to ConnectionStrings:DefaultConnection inside the application. Because environment variables can override JSON configuration, the same image can run against different databases in different environments.

Apply these rules to sensitive configuration:

  • Never commit passwords, tokens, or private keys to the Git repository.
  • Exclude local secret files and deployment output through .gitignore.
  • Use different credentials for production, staging, and testing.
  • Never write connection strings, authorization headers, or user passwords to logs.
  • If a secret is exposed, revoke and replace it instead of merely deleting the file.

3. Create a production publish output

Rather than running from source code, build and publish a release output before deployment. The following commands can be used locally or in CI:

dotnet restore
 dotnet build --configuration Release --no-restore
 dotnet test --configuration Release --no-build
 dotnet publish --configuration Release --output ./artifacts/publish --no-build

If your repository uses a solution file, explicitly specify the solution or project in real automation. Passing a build is not enough; successful tests provide stronger evidence that the release is safe. Also inspect the publish directory to ensure it does not contain development files, secrets, or unnecessary content.

4. Package the application with Docker

Docker packages the application and its runtime dependencies into a consistent image. A multi-stage Dockerfile uses the SDK image only for building and a smaller runtime image for execution.

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

COPY ["ContentPortal.csproj", "."]
RUN dotnet restore "ContentPortal.csproj"

COPY . .
RUN dotnet publish "ContentPortal.csproj" \
    --configuration Release \
    --output /app/publish \
    --no-restore

FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS final
WORKDIR /app

ENV ASPNETCORE_HTTP_PORTS=8080
EXPOSE 8080

COPY --from=build /app/publish .
USER app
ENTRYPOINT ["dotnet", "ContentPortal.dll"]

Change the project and DLL names if your application uses different names. ASP.NET Core .NET 8 container images can listen on port 8080 by default. The EXPOSE instruction documents the target port; when starting the container, you still need to map a host port to it.

Build and run the image locally:

docker build --tag content-portal:1.0.0 .
docker run --rm \
  --publish 8080:8080 \
  --env ASPNETCORE_ENVIRONMENT=Production \
  --env ConnectionStrings__DefaultConnection="Server=host.docker.internal;Database=ContentDb;User Id=appuser;Password=strong-password;TrustServerCertificate=True" \
  content-portal:1.0.0

Putting production credentials directly in a command line may expose them in process history on some systems. In a real environment, use a secret manager, Docker secrets, or protected application settings provided by the hosting platform.

5. Apply migrations in a controlled way

In development, dotnet ef database update is convenient. However, calling Database.Migrate() every time the production application starts can create race conditions when several application instances start together. Treat database migration as a controlled deployment step instead.

Generate a reviewable SQL script with:

dotnet ef migrations script --idempotent \
  --project ContentPortal.csproj \
  --output artifacts/migrate.sql

An idempotent script checks the database migration state and applies only the required changes. Run the script against staging first, inspect the generated SQL, and verify the backup and rollback plan before applying it to production. For larger systems, you can generate an EF migration bundle and execute it in a separate deployment job.

A migration review should answer these questions:

  • Has the migration been reviewed with the application change?
  • Could a column drop or rename cause data loss?
  • Has a production database backup been created?
  • Does the script start from the expected database state?
  • Is a maintenance window required for a long-running migration?

6. Configure a basic CI/CD workflow

Continuous integration means building and testing every change. Continuous delivery or deployment moves an approved artifact to staging or production. The following GitHub Actions workflow provides a basic CI pipeline:

name: build-and-test

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

jobs:
  verify:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v4

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

      - name: Restore
        run: dotnet restore

      - name: Build
        run: dotnet build --configuration Release --no-restore

      - name: Test
        run: dotnet test --configuration Release --no-build --verbosity normal

      - name: Publish
        run: dotnet publish --configuration Release --output artifacts/publish --no-build

In the CD stage, build the Docker image, push it to a container registry, and start the new tag on the hosting platform. Instead of using only latest, tag images with a commit SHA or release number so that you can identify exactly which code is running. For example, use content-portal:2026.10.30 or content-portal:${{ github.sha }}.

Protect the production deployment with an approval rule, environment protection settings, and limited secret access. Separating verification and deployment jobs prevents a failed test from accidentally reaching production.

7. Post-deployment verification

Opening the home page is not enough after deployment. Complete the following checks:

  1. Confirm from the startup logs that the application is running in the expected production environment.
  2. Verify that /health returns a successful response.
  3. Check the HTTPS certificate and confirm that HTTP requests redirect to HTTPS.
  4. Test sign-in, role checks, content listing, content creation, and file upload flows.
  5. Verify the database connection, migration state, and critical tables.
  6. Confirm that 404, 500, and unauthorized requests produce the expected responses.
  7. Review logs for exceptions, connection failures, and repeated warnings.
  8. Check caching, static files, robots.txt, and sitemap behavior prepared in earlier lessons.
  9. Confirm that backups run successfully and that the restore procedure is documented.
  10. Test the rollback procedure by identifying the previous image tag.

Common mistakes

  • Deploying development settings: Detailed exception pages and test users create security risks.
  • Committing secrets: Even after deleting a commit, the value may remain in other copies; revoke and rotate it.
  • Leaving migrations to application startup: Multiple instances can apply schema changes without proper coordination.
  • Mapping the wrong container port: Keep the .NET 8 container port separate from the host port.
  • Only running a build: Tests, health checks, critical user flows, and rollback procedures also need verification.
  • Using no immutable release identifier: A single latest tag makes the running version difficult to identify.

Short practice exercise

Create the following deployment plan for your application:

  1. Create an appsettings.Production.json file containing no secrets.
  2. Add a multi-stage Dockerfile and run the application on port 8080.
  3. Start a local container and test the /health endpoint.
  4. Generate an idempotent migration script and apply it to a staging database.
  5. Run restore, build, test, and publish through GitHub Actions.
  6. Add the post-deployment checklist to the repository as a Markdown document.

Conclusion

Production deployment is much more than running a single command. Secure configuration, a correct container image, controlled migrations, automated tests, approved releases, and post-deployment monitoring must be considered together. With the workflow from this lesson, the ASP.NET Core MVC application can run consistently across environments and new versions can be released with less risk.

At the end of this course, you now know not only how to build an MVC application, but also how to expose it to real users in a testable, secure, observable, and maintainable way.

Sources