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:
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.
1Pass .NET Connection Strings via Docker Environment Variables
.envASP.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.
.envdotenvASPNETCORE_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"2Persist ASP.NET Core Data Protection Keys in Redis
Program.csStore Data Protection keys in your Redis container so rebuilding the ASP.NET Core image never logs out cookie-authenticated users.
Program.cscsharpusing Microsoft.AspNetCore.DataProtection; using StackExchange.Redis; var redis = ConnectionMultiplexer.Connect( builder.Configuration.GetConnectionString("Redis")!); builder.Services.AddDataProtection() .PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys");3Build a Non-Root .NET 8/9 Multi-Stage Dockerfile Listening on Port 8080
DockerfileOfficial .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.
DockerfiledockerfileFROM 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"]4Boot the Stack and Inspect Container Health Checks
terminalValidate YAML interpolation, launch containers, and inspect Kestrel startup logs after PostgreSQL and Redis report healthy.
terminalbashdocker 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.
.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.
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.
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.
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:
Validate ASP.NET Core 8/9 Linux and Docker .env files locally. Map double-underscore __ hierarchy keys to appsettings.json, ConnectionStrings, and CORS arrays.
Build a production Nginx reverse proxy for ASP.NET Core 8/9 Kestrel on port 5000 with UseForwardedHeaders, SignalR WebSockets, SSL, and large OAuth headers.
Fix CORS errors between ASP.NET Core 8/9 Web API and Angular CLI on port 4200. Verify UseCors middleware ordering, AllowCredentials, and HTTPS redirects.
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.
Related Docker Compose Stack Guides
Browse all 10 Compose stacks →Docker Compose FastAPI + PostgreSQL 16 + Celery Worker Healthcheck Guide
Build a production Docker Compose stack for Python FastAPI, PostgreSQL 16, Redis 7, and Celery workers with pg_isready healthchecks and Alembic migrations.
Docker Compose Next.js Standalone + Prisma + PostgreSQL 16 Stack Guide
Generate a Docker Compose config for Next.js App Router standalone output with Prisma ORM and PostgreSQL 16 using pg_isready healthchecks and service DNS.
Docker Compose Laravel Octane + PostgreSQL 16 + Reverb WebSockets Guide
Generate a Docker Compose stack for Laravel Octane, PostgreSQL 16, Redis 7, and Laravel Reverb WebSockets with pg_isready healthchecks and firewall safety.
Docker Compose Node.js + BullMQ Worker + Redis 7 + PostgreSQL 16 Guide
Generate a Docker Compose config for Node.js APIs, BullMQ background workers, Redis 7, and PostgreSQL 16 with native healthchecks and noeviction Redis safety.