Docker Compose Builder · .NET / ASP.NET Core + Postgres

Docker Compose ASP.NET Core 8/9 + PostgreSQL 16 + Redis Cache Guide

Generate a Compose Specification docker-compose.yml and matching .env.example for .NET / ASP.NET Core + Postgres with native binary healthchecks, service_healthy boot ordering, and firewall-safe port bindings.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust stack settings or load a test scenario2. Inspect live diagnostics3. Copy generated config
Quick-Test Scenarios:

1. Runtime & Data Services

2. Healthchecks, Workers & Security

# docker-compose.yml — Modern Compose Specification (no obsolete 'version:' attribute)
# Generated by OpsCheck DevTools (ASP.NET Core)
name: dotnet_postgres_stack

services:
  api:
    build:
      context: .
      dockerfile: Dockerfile
    restart: unless-stopped
    env_file:
      - .env
    ports:
      - "127.0.0.1:8080:8080"
    environment:
      DB_HOST: postgres
      DB_PORT: "5432"
      REDIS_HOST: redis
      REDIS_PORT: "6379"
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_healthy
    networks:
      - app_network

  postgres:
    image: postgres:16-alpine
    restart: unless-stopped
    environment:
      POSTGRES_DB: ${DB_DATABASE:-app_db}
      POSTGRES_USER: ${DB_USERNAME:-app}
      POSTGRES_PASSWORD: ${DB_PASSWORD:-change_me_strong}
    # Kept strictly internal on app_network (prevents Docker iptables UFW bypass)
    expose:
      - "5432"
    volumes:
      - db_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER:-app} -d $${POSTGRES_DB:-app}"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 20s
    networks:
      - app_network

  redis:
    image: redis:7-alpine
    command: redis-server --appendonly yes
    restart: unless-stopped
    expose:
      - "6379"
    volumes:
      - redis_data:/data
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 10s
    networks:
      - app_network

networks:
  app_network:
    driver: bridge

volumes:
  db_data:
  redis_data:
Service Boot Orderbridge: app_network
postgres(healthy)+redis(healthy)api

Healthcheck & Security Diagnostics

Compose Spec v2+
  • passStartup Race Condition Prevented (condition: service_healthy)

    api will wait until postgres and redis pass their native healthchecks before starting.

  • infoInternal Bridge DNS Hostnames (Never Use localhost Inside Containers)

    Connect over the shared app_network using Docker service names: DB_HOST=postgres (port 5432), REDIS_HOST=redis (port 6379). Inside the "api" container, 127.0.0.1/localhost points only to "api" itself and always refuses DB/broker connections.

  • passFirewall-Safe Port Exposure Enabled (127.0.0.1 / Internal expose:)

    Database and broker ports stay strictly isolated on app_network via expose:, and app ports bind to 127.0.0.1 so Docker never bypasses host UFW/nftables rules.

  • passNative Probe Binaries Used (pg_isready & redis-cli ping)

    Generated healthchecks invoke built-in service binaries rather than curl or wget, avoiding false "unhealthy" states in minimal Alpine and slim official images.

  • passPersistent Named Volumes Declared (db_data, redis_data)

    Top-level named volumes preserve database tables and broker queues across container rebuilds and "docker compose down" (data is only removed if you pass -v).

Runs locally in your browser. Compose YAML and environment templates are generated client-side.

Typical Container Boot & Connection Error (.NET / ASP.NET Core + Postgres)

When depends_on lacks condition: service_healthy or internal service hostnames are misconfigured in .env, container logs typically surface this error during startup:

docker compose logs (Startup Failure)

Npgsql.NpgsqlException (0x80004005): Failed to connect to 127.0.0.1:5432 ---> System.Net.Sockets.SocketException (111): Connection refused

Container Boot Ordering, Bridge DNS & Persistence for .NET / ASP.NET Core + Postgres

Containerizing an ASP.NET Core 8 or 9 Web API with Entity Framework Core (Npgsql), PostgreSQL 16, and StackExchange.Redis inside Docker Compose gives .NET teams identical local and production environments on Linux. Starting in .NET 8, Microsoft changed the default non-root container HTTP port from 80 to 8080 (via ASPNETCORE_HTTP_PORTS=8080), which catches many teams migrating older Dockerfiles.

When an ASP.NET Core container runs EF Core migrations on startup or initializes IDistributedCache via StackExchange.Redis, standard list-style depends_on causes immediate SocketException (111) Connection refused or RedisConnectionException crashes because PostgreSQL and Redis have not finished binding sockets. Wiring pg_isready and redis-cli ping healthchecks with condition: service_healthy holds Kestrel cleanly until both services pass readiness probes.

Inside appsettings.json or Docker environment variables, .NET double-underscore overrides (ConnectionStrings__DefaultConnection and ConnectionStrings__Redis) MUST reference the Docker Compose service names ("Host=postgres;Port=5432;.." and "redis:6379") rather than localhost. Remember also to set abortConnect=false on StackExchange.Redis connection strings so brief Redis reloads do not permanently crash the API singleton.

Keeping PostgreSQL (5432) and Redis (6379) private via expose: on app_network and binding Kestrel strictly to 127.0.0.1:8080:8080 behind a host Nginx reverse proxy prevents Docker iptables rules from exposing databases or unencrypted Kestrel ports directly to the internet.

Finally, because ASP.NET Core Data Protection keys (used for antiforgery tokens and cookie encryption) default to container-local ephemeral storage, persist keys to Redis (PersistKeysToStackExchangeRedis) or a named Docker volume so container restarts do not invalidate logged-in user sessions.

For production ASP.NET Core 8 and 9 Docker Compose deployments, wire .NET's built-in /healthz endpoint (AddHealthChecks().AddNpgSql().AddRedis()) alongside Compose's PostgreSQL and Redis healthchecks so orchestrators and host Nginx proxies can verify end-to-end API readiness. Keeping Data Protection keys persisted in Redis and container logs rotated cleanly makes single-host .NET container operations predictable and low-maintenance.

Step-by-Step .NET / ASP.NET Core + Postgres Docker Compose Setup Guide

Follow each step below to pair the generated Compose file with accurate container DNS variables, safe database migrations, and zero-downtime restarts.

  1. 1Pass .NET Connection Strings via Docker Environment Variables

    .env

    ASP.NET Core automatically maps double-underscore environment variables to appsettings.json sections. Use service names "postgres" and "redis" plus abortConnect=false for resilient Redis reconnects.

    .envdotenv
    ASPNETCORE_ENVIRONMENT=Production
    ASPNETCORE_HTTP_PORTS=8080
    
    DB_DATABASE=app_db
    DB_USERNAME=app
    DB_PASSWORD=change_me_strong
    
    ConnectionStrings__DefaultConnection="Host=postgres;Port=5432;Database=app_db;Username=app;Password=change_me_strong"
    ConnectionStrings__Redis="redis:6379,abortConnect=false"
  2. 2Persist ASP.NET Core Data Protection Keys in Redis

    Program.cs

    Store Data Protection keys in your Redis container so rebuilding the ASP.NET Core image never logs out cookie-authenticated users.

    Program.cscsharp
    using Microsoft.AspNetCore.DataProtection;
    using StackExchange.Redis;
    
    var redis = ConnectionMultiplexer.Connect(
        builder.Configuration.GetConnectionString("Redis")!);
    
    builder.Services.AddDataProtection()
        .PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys");
  3. 3Build a Non-Root .NET 8/9 Multi-Stage Dockerfile Listening on Port 8080

    Dockerfile

    Official .NET 8/9 aspnet runtime images run as the non-root "app" user on port 8080 by default; matching appPort: 8080 in your Compose configuration.

    Dockerfiledockerfile
    FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
    WORKDIR /src
    COPY . .
    RUN dotnet publish -c Release -o /app/publish
    
    FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS runtime
    WORKDIR /app
    USER $APP_UID
    EXPOSE 8080
    COPY --from=build /app/publish .
    ENTRYPOINT ["dotnet", "Api.dll"]
  4. 4Boot the Stack and Inspect Container Health Checks

    terminal

    Validate YAML interpolation, launch containers, and inspect Kestrel startup logs after PostgreSQL and Redis report healthy.

    terminalbash
    docker compose config --quiet && docker compose up -d --build
    docker compose ps
    docker compose logs -f api

Common .NET / ASP.NET Core + Postgres Docker Compose Pitfalls

Avoid these three container orchestration mistakes before deploying your Compose stack onto staging or production servers.

Pitfall 1

.NET 8/9 Non-Root Port 8080 vs. Legacy Port 80 Mismatch

Upgrading from .NET 7 to .NET 8/9 switches the default container listening port from 80 to 8080 because non-root users cannot bind privileged port 80. Mapping "5000:80" in Compose then causes immediate connection refused errors.

Pitfall 2

StackExchange.Redis Throwing Fatal Exceptions Without abortConnect=false

By default, StackExchange.Redis aborts permanently if Redis blips during startup. Always append abortConnect=false to ConnectionStrings__Redis alongside Compose's redis-cli ping healthcheck.

Pitfall 3

EF Core Migrate() Races When Scaling API Containers

Calling dbContext.Database.Migrate() inside Program.cs works on a single container, but scaling to 2+ API replicas causes concurrent schema-lock errors. Use EF Core migration bundles (efbundle) in CI/CD for multi-replica deployments.

Related Tools

Pair Your Docker Compose Stack With .env Linting, Nginx TLS & CORS Checks

Validate your .env file for unescaped $$ interpolation or leaked secrets, configure Nginx DNS resolution, and verify cross-origin headers:

Frequently Asked Questions

Why does Npgsql still try 127.0.0.1:5432 even when PostgreSQL is running in Docker?
Your appsettings.Development.json or fallback connection string specifies Host=localhost. Inside Docker Compose, override ConnectionStrings__DefaultConnection with Host=postgres so Npgsql resolves the sibling container over app_network.
Should I run Kestrel HTTPS inside the Docker container behind Nginx?
No. Let Nginx terminate public TLS on port 443 and forward plain HTTP to Kestrel on port 8080 inside the private Docker bridge network, with app.UseForwardedHeaders() registered first in Program.cs.
How do I add a .NET BackgroundService Worker container to this stack?
Toggle "Include Background Queue Worker" in the builder above; it generates a sibling worker service sharing the same image, .env file, and service_healthy dependencies.
Why does docker compose up recreate my Postgres volume when I rename the folder?
Docker Compose prefixes named volumes with the project name (which defaults to the directory name). Setting an explicit top-level name: in docker-compose.yml (generated automatically above) prevents accidental volume orphaning if directories move.
Browse all 10 Compose stacks →