October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

Docker Compose: Run a Web App with PostgreSQL and Redis

A practical Compose template for running a web app with PostgreSQL and Redis, including readiness checks, service networking, and data-lifecycle guidance.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Define your app, PostgreSQL, and Redis as services in compose.yaml. From the web container, connect to the other services by their Compose service names—db and redis—not localhost. Add healthchecks and long-form depends_on conditions if the app must wait for those services to become ready, and store PostgreSQL data in a named volume.

Define the three services in compose.yaml

This starting template uses Docker’s documented PostgreSQL and Redis healthcheck patterns. Replace the build context, environment variable names, credentials, and image tags with values appropriate to your application. The postgres:18 and redis:alpine tags are examples, not universal version recommendations; confirm compatibility with your app and deployment target.

As an Amazon Associate I earn from qualifying purchases.

services:
  web:
    build: .
    ports:
      - "8000:8000"
    environment:
      DATABASE_URL: postgresql://app:${POSTGRES_PASSWORD}@db:5432/app
      REDIS_URL: redis://redis:6379
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_healthy

  db:
    image: postgres:18
    environment:
      POSTGRES_DB: app
      POSTGRES_USER: app
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
    volumes:
      - postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
      interval: 10s
      timeout: 10s
      retries: 5
      start_period: 30s

  redis:
    image: redis:alpine
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 5
      start_period: 10s

volumes:
  postgres_data:

How the connections work

Compose creates a network for the services. The web app reaches PostgreSQL at host db and Redis at host redis, using each service’s container port. In this example those ports are 5432 and 6379. The 8000:8000 mapping publishes the web service’s port 8000 on the host; it does not change how containers address one another.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The connection-string formats are examples. Use the environment variable names and URL syntax expected by your framework and configure any required database name, username, password, TLS, or other options accordingly.

Why the PostgreSQL healthcheck uses $$

Compose normally interpolates dollar-sign variables while it reads the file. Doubling the dollar sign in $${POSTGRES_USER} and $${POSTGRES_DB} defers expansion to the shell inside the container, where those environment variables are available. The check runs pg_isready with the configured database user and name.

Start the stack and check its state

  1. From the directory containing compose.yaml, start and build the services:

    docker compose up --build
  2. In another terminal, inspect service status:

    docker compose ps
  3. Follow logs from the app and its dependencies:

    docker compose logs -f web db redis

The Redis check uses redis-cli ping, which tests whether Redis responds to that probe. A healthy status for either dependency means its configured check succeeded; it does not prove that the web app’s credentials, schema, migrations, or application-level operations are correct.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Understand startup order versus readiness

Short-form depends_on controls startup order, but it does not make Compose wait for a dependency to become ready. Docker documents that Compose waits for a container to be running—not ready—unless readiness is handled separately. With a healthcheck and condition: service_healthy, Compose waits for the dependency’s configured healthcheck to pass before starting the dependent service. See Docker’s startup-order guide and service reference.

Healthchecks are bounded probes, not an application readiness guarantee. Their result depends on the command and timing settings you configure. Your app should still handle failed connections and, where appropriate, retry operations if a dependency becomes unavailable after startup.

Keep PostgreSQL data across container removal

The postgres_data named volume is mounted at PostgreSQL’s data directory. It keeps database files outside the container’s writable layer, so removing and recreating the container does not by itself erase the volume’s contents.

To stop the services and remove their containers and default network while retaining named-volume data, run:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
docker compose down

Do not add -v when you want to preserve the volume. Removing volumes can delete persisted state, so check what data the project needs before doing so. Docker’s Compose Quickstart demonstrates the volume and data lifecycle.

Best Value
Docker Container Linux Devops Programming Coding T-Shirt
  • Docker, Docker Swarm, Docker Compose, Programmer, Developer, Coding, Programming, Software Engineer, Code, DevOps, Deploy, Deployment, Kubernetes, Salt, Puppet, Chef, Terraform, Container, AWS, Azure, Cloud, Geek, Funny, Computer, Software, Tech, IT
  • Integration, Scrum, Compile, Compilation, Science, Bug, Debug, Python, Linux, Java, Javascript, Scala, Dotnet, Kotlin
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem

PostgreSQL initialization happens on an empty data directory

The official PostgreSQL image’s initialization environment variables and initialization scripts apply when the data directory is first initialized. Changing POSTGRES_PASSWORD, POSTGRES_USER, or POSTGRES_DB later does not reinitialize an existing volume. The image documentation also notes that if an initialization script fails after the data directory has been initialized, restarting the container does not automatically resume the remaining scripts. Diagnose the failure and choose a deliberate recovery plan rather than assuming a restart will rerun initialization. See the official PostgreSQL image documentation.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Decide whether Redis data should persist

A Redis volume is not included in this template because the right policy depends on Redis’s role. If it is only a cache whose contents can be rebuilt, disposable data may be appropriate. If it holds queue state or other data the application cannot afford to lose, decide on persistence, backups, and recovery deliberately; simply adding a volume does not define a complete policy. Docker’s Quickstart shows a Redis named-volume example, but your application’s requirements determine whether and how to use one.

Protect credentials and plan for the target environment

The example references POSTGRES_PASSWORD without embedding its value in the Compose file. For local development, provide it through an environment file excluded from version control or another suitable local mechanism. For deployment, use the secrets handling appropriate to that environment; Docker’s Node.js guide demonstrates Compose secrets. Never commit real credentials to a shared repository.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A local Compose stack does not, by itself, provide a production security, backup, high-availability, monitoring, or disaster-recovery design. Select supported database and Redis versions, image tags, and migration strategies for the actual application and deployment target.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.