Skip to content
shellhacks.dev
Databases

Check if Postgres is ready

Check whether PostgreSQL accepts connections with pg_isready. The exit status is 0 when ready, 1 when rejecting, 2 on no response and 3 on a bad call.

1 min read
Summarize in AI

A script or a container health check should wait until the database server is up before it runs a migration.

Shell
pg_isready -h 127.0.0.1 -p 5432; echo "exit: $?"
pg_isready -h 127.0.0.1 -p 5999 -t 2; echo "exit: $?"
until pg_isready -q -h 127.0.0.1; do sleep 1; done; echo "ready"
Text
127.0.0.1:5432 - accepting connections
exit: 0
127.0.0.1:5999 - no response
exit: 2
ready

pg_isready sends a connection probe without logging in, and reports through the exit status: 0 for accepting connections, 1 when the server is starting up or rejecting, 2 for no response, and 3 when no attempt was made, per the pg_isready reference. The -t option sets the timeout in seconds. In the loop, the quiet flag leaves the exit status as the only signal.

Ready means the server accepts connections, not that your database, user or tables exist. A fresh container starts a temporary server during initialization and then restarts, so a health check can pass early; confirm with a real query. Use -U and -d to make the probe match the real client.

Share

More snippets

Databases

Dump one table

Dump one table with pg_dump -t name. The option takes a pattern, so -t orders does not match orders_archive but -t 'orders*' does, and quoting rules apply.

2 min read
Databases

Run SQL from a file

Run SQL from a file with psql -f. An error in the middle does not stop the file and the exit status stays 0, unless ON_ERROR_STOP is set to 1.

2 min read
Databases

Describe a table

Show a table's columns, indexes and foreign keys with the psql meta-command backslash d, and add a plus sign for storage and comments.

2 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.