Skip to Content
DatabasePostgreSQL on Zenifra

Connect your application to PostgreSQL

This guide shows how to connect an application to Zenifra PostgreSQL with the most common Python, Node.js, Bun, PHP, and Go drivers. The connection strings in the Console already use TLS: with most drivers, you just paste the string, without code changes and without extra environment variables.

Using MariaDB? See Connect your application to MariaDB.

What TLS is

TLS encrypts everything between your application and the database: password, queries, and data. We recommend keeping it on.

  • PostgreSQL: requires TLS by default. You can stop requiring it at creation or later, in the database settings. See Require TLS on PostgreSQL.

Before you start

  1. Open the database in the Console and copy the connection string. The full password is shown only at creation or after a password rotation.
  2. In the application project, open Environment Variables and create DATABASE_URL with that string.
  3. Always use the host shown in the Console, in the postgresql-<id>.managed.zenifra.com format.

Summary by driver

LanguageDriverWhat to do
Terminalpsql, pg_dump, pg_restore, pgbenchUse the Console URI as is
Pythonpsycopg2, psycopg 3, asyncpg, SQLAlchemyUse the Console URI as is
Node.js and Bunpg (node-postgres), postgres (postgres.js), Bun.sqlUse the Console URI as is
Node.jsPrisma 6 and Prisma 7 (@prisma/adapter-pg)Use the Console URI as is
Gopgx and lib/pqUse the Console URI as is
PHPPDO (pdo_pgsql)Build the DSN with sslmode=require
PHPLaravelUse the Console URI in DB_URL
PHPSymfony (Doctrine)Use the Console URI in DATABASE_URL and add serverVersion

Connection string

The PostgreSQL URI in the Console has this format:

postgresql://app:<password>@<host>:<port>/app?sslmode=require

sslmode=require turns TLS on in every driver in the table above, with no code changes, no sslrootcert, no CA bundle, and no environment variable. If your application already stores the old URI (postgres://…?sslmode=verify-full&sslrootcert=system), it keeps working wherever it already worked. If you used a workaround for it (removing sslrootcert from the URI, ssl: true in node-postgres, an SSL context in asyncpg, SSL_CERT_FILE), switch to the new URI and remove the workaround.

psql

psql "$DATABASE_URL"

pg_dump, pg_restore, and pgbench accept the same URI.

Python

import os
import psycopg  # or psycopg2

with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
    conn.execute("SELECT 1")
import os
import asyncpg

conn = await asyncpg.connect(os.environ["DATABASE_URL"])
import os
from sqlalchemy import create_engine

engine = create_engine(os.environ["DATABASE_URL"])

Django and other frameworks that use psycopg or psycopg2 underneath follow the same rule: pass the URI as is.

Node.js and Bun with pg (node-postgres)

import pg from 'pg'

const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL })
await pool.query('SELECT 1')

pg prints a SECURITY WARNING about the meaning of sslmode=require. This is expected: the connection uses TLS normally.

Node.js and Bun with postgres.js

import postgres from 'postgres'

const sql = postgres(process.env.DATABASE_URL)
await sql`SELECT 1`

Bun with Bun.sql

const sql = new Bun.SQL(process.env.DATABASE_URL)
await sql`SELECT 1`

Prisma

On Prisma 6, use the URI in url = env("DATABASE_URL") in the datasource of schema.prisma. On Prisma 7, pass the URI to the @prisma/adapter-pg adapter:

import { PrismaClient } from '@prisma/client'
import { PrismaPg } from '@prisma/adapter-pg'

const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
const prisma = new PrismaClient({ adapter })

Go with pgx or lib/pq

conn, err := pgx.Connect(ctx, os.Getenv("DATABASE_URL"))
db, err := sql.Open("postgres", os.Getenv("DATABASE_URL")) // lib/pq

Connecting with separate fields

If the application builds the connection from separate host, port, user, and password fields, pg, postgres.js, and Bun.sql do not ask for TLS, and the database rejects the connection with an error that contains no encryption. Prefer the URI. If you need the fields, add ssl: true to the driver configuration:

const pool = new pg.Pool({ host, port, user, password, database, ssl: true })

PHP with PDO (pdo_pgsql)

PDO does not read the URI. Build the DSN from its parts and sslmode=require:

<?php
$url = parse_url(getenv('DATABASE_URL'));
$pdo = new PDO(
    sprintf(
        'pgsql:host=%s;port=%d;dbname=%s;sslmode=require',
        $url['host'],
        $url['port'],
        ltrim($url['path'], '/'),
    ),
    rawurldecode($url['user']),
    rawurldecode($url['pass']),
);

Laravel with PostgreSQL

DB_CONNECTION=pgsql
DB_URL=<Console URI>

Laravel passes the URI's sslmode to the driver, and php artisan migrate uses the same connection. Prefer DB_URL over DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME, and DB_PASSWORD: that way, the connection follows the Console URI.

Symfony with Doctrine and PostgreSQL

Add serverVersion with the database major version (16, 17, or 18) to the end of the Console URI:

DATABASE_URL=postgresql://app:<password>@<host>:<port>/app?sslmode=require&serverVersion=17

Without serverVersion, DoctrineBundle fails before connecting, with Invalid platform version "" specified. The default config/packages/doctrine.yaml (url: '%env(resolve:DATABASE_URL)%') works without changes, and Doctrine passes the URI's sslmode to the driver.

Verify the certificate (optional)

sslmode=require encrypts the connection. If you also want the driver to check the database certificate, use sslmode=verify-full&sslrootcert=system instead of sslmode=require, on drivers that support this option. The certificate is public, issued for *.managed.zenifra.com, so always connect through the Console host, not the IP. This is an advanced setting: the default path is the Console URI.

Require TLS on PostgreSQL

TLS is on by default. When you create the database, the Require TLS (encrypted connection) switch is already on. Later, in the database settings, the TLS card has the Require TLS switch.

  • On (recommended): the database only accepts encrypted connections. A connection without TLS is rejected with an error that contains no encryption.
  • Off: the database also accepts unencrypted connections, for drivers that do not use TLS. The connection strings in the Console still use TLS.

Connections without TLS travel in the clear over the internet. Turn it off only if your application cannot use TLS. When you turn it off, the Console asks for confirmation; you can turn it back on at any time. The change requires the database to be running and the same permission that changes the database's public access. See the steps in How to Change PostgreSQL Settings.

Common errors

MessageCauseHow to fix
Error with no encryption on PostgreSQLThe driver connected without TLS and the database requires TLSUse the Console URI; with separate fields, add ssl: true, as in Connecting with separate fields
SECURITY WARNING in pg (node-postgres)Driver notice about sslmode=requireNothing to do: the connection uses TLS
ENOENT: no such file or directory, open 'system', FileNotFoundError in asyncpg, or SSL error: certificate verify failedThe application uses the old URI, with sslrootcert=systemSwitch to the current Console URI, with ?sslmode=require
root certificate file ".../.postgresql/root.crt" does not existsslmode=verify-full without sslrootcert=systemUse the Console URI, with ?sslmode=require, or add sslrootcert=system
Hostname/IP does not match certificate's altnames or IP address mismatchThe connection uses an IP or another name instead of the Console hostUse the exact host shown in the Console
Invalid platform version "" specifiedDoctrineBundle needs serverVersion in the PostgreSQL URIAdd &serverVersion=<version> to the URI
password authentication failed or Access deniedThe password in DATABASE_URL is not the current oneCheck the password or generate a new one in the database settings and update the application variable

Next steps

Last updated on

On this page