Back to Blog
DevOps•5 min read

Fix Docker App Cannot Connect to Its Database

DockerPostgreSQLNetworking

In this guide

Fix Docker database connection failures by checking service hostnames, container ports, shared networks, readiness checks, and application retries.

When a Docker app cannot connect to its database, check the hostname from inside the app container. In a normal Compose network, localhost identifies that container, not the database service. Use the database service name and internal port, then verify network membership, readiness, and application credentials.

What does connection refused actually tell you?

In an illustrative deployment, PostgreSQL works from a desktop database client through port 5433, but a containerized API cannot connect. The API uses localhost:5433, copied from the desktop settings. That address points at the API container itself. The host's published port and the database's container port serve different connection paths.

Separate the error classes before editing configuration. Name resolution failure suggests a hostname or network issue. Connection refused suggests that the destination is reachable but nothing is listening at that address and port. Authentication errors suggest the network path works far enough to reach the database. Each observation narrows the next check.

Step 1: draw the connection from its actual origin

Write down where the client runs: host machine, application container, another Compose project, or an external service. For containers in the same Compose network, use the service name such as db and PostgreSQL's internal port, commonly 5432. From a host tool, use the published host port if one is deliberately configured.

Do not hardcode a container IP observed during debugging. Containers can be replaced and receive different addresses. Service discovery exists so the application can use a stable service name. If two services belong to different projects, explicitly plan a shared network or another supported connection path rather than assuming their default networks are shared.

Step 2: inspect services and test from the app container

  1. Run docker compose ps and confirm that the database container is running rather than repeatedly restarting.
  2. Inspect database logs for initialization, storage, permissions, or configuration failures. Redact credentials before sharing output.
  3. Check the effective application host and port without printing the full connection URL or password.
  4. Use a diagnostic client from the same application network to test name resolution, reachability, and authentication separately.
  5. Confirm that both services are attached to the intended network and that the database listens on the expected interface.

A minimal production image may not include a shell, DNS tools, or a database client. Use an authorized temporary diagnostic container on the same network rather than adding troubleshooting packages permanently to the application image. Remove that diagnostic container when the investigation is finished.

Step 3: add an explicit database readiness check

The following Compose fragment assumes an existing app service with its image or build configured elsewhere. It uses environment variables supplied outside the file. It intentionally publishes no database port to the host because the illustrated API connects over the internal network.

yaml
services:
  app:
    environment:
      DB_HOST: db
      DB_PORT: "5432"
    depends_on:
      db:
        condition: service_healthy
  db:
    image: postgres:18
    environment:
      POSTGRES_USER: ${DB_USER:?Set DB_USER}
      POSTGRES_PASSWORD: ${DB_PASSWORD:?Set DB_PASSWORD}
      POSTGRES_DB: ${DB_NAME:?Set DB_NAME}
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
      interval: 5s
      timeout: 3s
      retries: 12

Choose a supported database image version compatible with your application and persistence layout. The example illustrates readiness, not a complete production database configuration. Add durable storage, backups, resource planning, and a secret-management approach appropriate to the environment before using a containerized database for live records.

Step 4: distinguish readiness from valid application access

A readiness probe answers a narrow question. pg_isready can indicate that PostgreSQL accepts connections without proving that the application's specific password, database, schema, and permissions are correct. Follow it with an application-level check that performs the minimum required authenticated operation.

Avoid a health endpoint that performs expensive reports on every probe. A small, bounded check is easier to interpret and less likely to cause load during an incident. Keep dependency health separate from a process liveness check so an external outage does not trigger an endless restart loop for otherwise functioning application processes.

Step 5: handle a later database restart

Startup ordering helps the first launch. The database can still restart after the API is already running. Configure connection recovery, bounded retry, and useful error reporting in the application. Do not assume that one successful startup check guarantees database availability for the lifetime of the deployment.

Test a controlled database restart in staging. Confirm that the API reports temporary unavailability clearly, recovers connections, and avoids repeating unsafe writes. A retryable connection attempt is different from blindly replaying a transaction whose outcome is unknown. Use business-level idempotency when a request may have committed before the connection failed.

Why does changing the password variable not fix login?

Database container initialization settings and existing database users are different things. Once a persistent database exists, editing a Compose environment variable does not necessarily change a stored user’s password. Inspect the image’s documented initialization behavior and use an authorized database credential-change procedure for existing data.

Do not remove a live volume to force initialization to run again. That can destroy the records you are trying to restore access to. Confirm backups, identify the existing database instance, and change only the intended credential or application setting. Update dependent services consistently and test a new connection. This distinction is especially useful when networking now works but the error has changed from connection refused to password authentication failed.

Retest the exact original connection path after the change, including a fresh deployment and a second restart. Document the host-versus-container port mapping for developers. For setup context, read our Docker Compose guide. Explore backend and cloud development or send a redacted network diagram and error for a scoped review.

Official references and further reading

Docker: networking in Compose

Docker: startup order and service readiness

PostgreSQL: pg_isready

Relevant Scaleup Infotech Services

Share this article:

Keep Reading

Ready to implement these ideas?

Discuss Your Project