Running a .NET API with PostgreSQL and Redis locally using Docker Compose

With docker compose: the API, PostgreSQL and Redis start with a single command, the same for the whole team.

yaml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# ======================================================================
# Q: How do you run the service and its dependencies locally?
#
# With docker compose: the API, PostgreSQL and Redis start with a single
# command, the same for the whole team.
# - __ (double underscore) in environment variables maps to : in configuration:
#   ConnectionStrings__Default = ConnectionStrings:Default.
# - Inside a container, localhost is the container itself. Other services are
#   reached by their name (db, redis).
# - Alternatively .NET Aspire (Q33): the same idea, but in C#, with a dashboard
#   for logs and traces.
# ======================================================================

# docker-compose.yml: API, PostgreSQL and Redis
services:
  api:
    build: .
    ports: ["8080:8080"]
    environment:
      ASPNETCORE_ENVIRONMENT: Development
      ConnectionStrings__Default: "Host=db;Database=shop;Username=shop;Password=dev-only"
      ConnectionStrings__Redis: "redis:6379"
    depends_on:
      db:    { condition: service_healthy }   # waits until the database is ready
      redis: { condition: service_started }

  db:
    image: postgres:16-alpine
    environment: { POSTGRES_DB: shop, POSTGRES_USER: shop, POSTGRES_PASSWORD: dev-only }
    volumes: [pgdata:/var/lib/postgresql/data]
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U shop"]
      interval: 5s
      retries: 10

  redis:
    image: redis:7-alpine

volumes:
  pgdata: