Dev Overflow Logo

Dev Overflow

Global search

Search across questions, answers, users and tags.

Docker Compose: how do I wait for Postgres to be ready before starting my app?

clock icon

asked 3 months ago

message icon

2

eye icon

1.1K

depends_on starts the database container first, but my app still crashes on boot because Postgres isn't accepting connections yet. Adding sleep 10 works but feels awful.

2 Answers

depends_on alone only waits for the container to start, not for the process inside to be ready. Add a healthcheck and depend on that condition:

1services:
2 db:
3 image: postgres:17
4 healthcheck:
5 test: ["CMD-SHELL", "pg_isready -U postgres"]
6 interval: 5s
7 timeout: 3s
8 retries: 10
9
10 app:
11 depends_on:
12 db:
13 condition: service_healthy
1services:
2 db:
3 image: postgres:17
4 healthcheck:
5 test: ["CMD-SHELL", "pg_isready -U postgres"]
6 interval: 5s
7 timeout: 3s
8 retries: 10
9
10 app:
11 depends_on:
12 db:
13 condition: service_healthy

That said — make the app retry its initial connection anyway. In production there is no Compose orchestrating startup order, and databases restart independently of your app. The healthcheck fixes local development; retry logic fixes reality.

Second the retry point. Exponential backoff with a cap, and log each attempt — otherwise a misconfigured host string looks identical to a slow-starting database.

1

of 1

Write your answer here

Introduce the problem and expand on what you've put in the title.

Top Questions