Skip to content
Latchkey

createdb: Create a PostgreSQL Database in CI

createdb dbname creates a new PostgreSQL database without opening psql, handy in CI setup steps.

createdb is a thin wrapper around CREATE DATABASE. In a pipeline it gives you a fresh test database in one line before migrations run, without writing SQL or entering psql.

What it does

createdb connects to a PostgreSQL server and issues CREATE DATABASE for the name you pass. Connection flags mirror psql (-h, -p, -U, and PGPASSWORD). Options let you set the owner, encoding, and a template database.

Common usage

Terminal
# create a test database owned by the app user
PGPASSWORD=secret createdb -h db -U postgres -O app appdb_test
# UTF-8 encoding from a clean template
createdb -h db -U postgres -E UTF8 -T template0 appdb_test

Options

FlagWhat it does
-O <owner>Role that will own the new database
-T <template>Template database to clone (template0 or template1)
-E <encoding>Character-set encoding, e.g. UTF8
-h / -p / -UStandard connection flags
-eEcho the SQL that createdb runs

In CI

Create the database after pg_isready confirms the server is up. Postgres service-container images often auto-create a database named by POSTGRES_DB, in which case createdb is redundant and will error that it already exists; either skip it or use template0 and a unique name. Connect as a role with CREATEDB privilege (postgres by default).

Common errors in CI

"createdb: error: database creation failed: ERROR: database \"appdb_test\" already exists" means it was already created (often by POSTGRES_DB); drop it first or skip. "ERROR: permission denied to create database" means the connecting role lacks CREATEDB; connect as postgres or grant it. "could not connect to server: Connection refused" means the server is not ready; gate with pg_isready.

Related guides

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