Skip to content
Latchkey

psql: Usage, Options & Common CI Errors

psql runs SQL against a PostgreSQL server, interactively or from a script.

psql is how pipelines seed databases and run migrations against a Postgres service container. The two recurring CI failures are password auth and connecting before the server is ready.

What it does

psql connects to a PostgreSQL server and executes SQL - interactively, from a single -c command, or from a -f file. In CI it targets a service container, so host, port, user, and password must all be supplied non-interactively.

Common usage

Terminal
PGPASSWORD=secret psql -h localhost -U postgres -d app -c 'SELECT 1'
psql -h localhost -U postgres -d app -f schema.sql
psql "postgresql://postgres:secret@localhost:5432/app" -c '\dt'
psql -h db -U postgres -d app -v ON_ERROR_STOP=1 -f migrate.sql

Options

FlagWhat it does
-h <host>Server host (CI service container hostname)
-p <port>Server port (default 5432)
-U <user>Connect as this role
-d <db>Database name
-c "SQL"Run one command and exit
-f <file>Run SQL from a file
-v ON_ERROR_STOP=1Exit non-zero on the first SQL error

Common errors in CI

psql: error: connection to server ... failed: FATAL: password authentication failed for user "postgres" - wrong/empty password; pass it via PGPASSWORD or the connection URI, not interactively. "could not connect to server: Connection refused / could not connect to server: No such file or directory" means the server is not up yet (race against the service container) or you used the default Unix socket instead of -h localhost - wait with pg_isready first. Without -v ON_ERROR_STOP=1, a failing statement in an -f script still exits 0, so broken migrations pass silently.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →