Connecting to PostgreSQL databases
Introduction
One of the first things you'll need to think about when working with a PostgreSQL database is how to connect and interact with the database instance. This requires coordination between the database client — the component you use to interact with the database, and the database server — the actual PostgreSQL instance that stores, organizes, and provides access to your data.
Because of this, you need to understand how to connect as a client by providing the required information to authenticate. In this guide, we'll cover how to connect to a PostgreSQL database using the native psql command line client — one of the most common and useful ways of interacting with a database instance.
In a companion guide, you can find out how to configure PostgreSQL's authentication to meet your project's needs. Consider reading both guides for a more complete picture of how authentication works in PostgreSQL.
If your database client or library requests a connection URI, you may want to look at our guide on understanding PostgreSQL connection URIs instead.
Basic information about the psql client
The psql client, the native command line client for PostgreSQL, can connect to database instances to offer an interactive session or to send commands to the server. It is especially useful when implementing your initial settings and getting the basic configuration in place, prior to interacting with the database through application libraries. In addition, psql is great for interactive exploration or ad-hoc queries while developing the access patterns your programs will use.
The way that you connect depends on the configuration of the PostgreSQL server and the options available for you to authenticate to an account. In the following sections, we'll go over some of the basic connection options. For clarity's sake, we'll differentiate between local and remote connections:
- local connection: a connection where the client and the PostgreSQL instance are located on the same server
- remote connection: where the client is connecting to a network-accessible PostgreSQL instance running on a different computer
Let's start with connecting to a database from the same computer.
Let Prisma Postgres handle the operations
Prisma Postgres provisions a fully managed Postgres database with automated backups and connection pooling — so you can focus on your app, not the infrastructure.
Connecting to a local database with psql
On Unix systems, psql without connection options normally uses a local Unix-domain socket. The default PostgreSQL user is your operating-system username, unless PGUSER or a connection option overrides it. The default database name is the selected PostgreSQL user, unless PGDATABASE or -d supplies another name. For example, psql -U app_user normally selects the database app_user, while psql -U app_user -d applicationdb selects applicationdb. PGHOST and PGPORT also override connection defaults; libpq environment variables list the full set.
Many Linux packages configure local sockets for peer authentication. This is an installation choice, not a universal PostgreSQL default. Peer authentication authenticates users automatically if a valid PostgreSQL user exists that matches the user's operating system username.
So if your current user is a valid PostgreSQL user on your local database, you can connect by typing:
Check your installation before assuming which account to use. Some macOS tools initialize a role matching your own account; containers have their own configured role, database and socket inside the container; managed services provide a hostname and credentials and do not give you the database server's operating-system account.
On Linux installations that create both a postgres operating-system account and a PostgreSQL administrator role and use peer authentication, you can connect as that operating-system account. The following sudo examples apply to those installations; they are not the application login path.
On such a Linux installation, use sudo to get a shell as the postgres user. To open a shell session for the postgres user and then log into the database, you can type:
If you don't need to perform any additional shell commands as the postgres user, you can also just run the psql command directly as the postgres user. This will log you in to a PostgreSQL session immediately instead of taking you to a shell first:
Either of these methods should allow you to log into the postgres PostgreSQL user account.
Connecting to a remote database
For security reasons and because of the reliance on a local socket file, peer authentication cannot be used for remote connections. Instead, users will need to log in using another method.
The available authentication methods vary based on the PostgreSQL instance's configuration. Most commonly, though, you will be able to authenticate by providing the following pieces of information:
| Option | Description |
|---|---|
| hostname | The network host name or the IP address of the PostgreSQL server. The -h option is used to specify the hostname. |
| network port | The network port that the PostgreSQL server is running on. By default, this is port 5432. This can be omitted if the default is used. To specify a different port, you can use the -p option. |
| PostgreSQL username | The database username you wish to connect as. If not specified, your operating system username will be used. The -U option is used to override the default and define the username to connect with. |
| PostgreSQL password | The PostgreSQL password associated with the specified username. Since psql will prompt you for a password if it isn't provided, this can often be omitted. |
| PostgreSQL database | The PostgreSQL database name that you want to access. If not specified and PGDATABASE is unset, the selected PostgreSQL username will be used as the database name. To specify a different database, use the -d option. |
There are multiple ways of providing your connection information to psql. Here, we'll cover the two of the most common: by passing options and with a connection string.
Passing connection information to psql with options
For remote connections, require TLS and verify the server's identity. Obtain the CA certificate from your provider's maintained instructions (for example, RDS certificates), or from your own trusted certificate authority. Use the hostname covered by the server certificate. Do not download a certificate from an unverified server and treat it as trusted.
The following template uses libpq environment options alongside the familiar psql flags. Replace the hostname, database, user and CA path. -W prompts for the password, keeping it out of the command and shell history:
verify-full checks both the certificate chain and hostname. A wrong-host certificate must fail. For unattended scripts, use a protected password file with mode 0600 on Unix rather than a password in a command-line argument. Use a role with only the privileges your application needs.
If psql reports that the server certificate does not match the host name, for example, server certificate for "db.example.test" does not match host name "wrong.example.test", check that the connection hostname matches a name in the certificate and that you have the intended server address. Correct the hostname or server certificate while retaining verify-full; disabling verification hides the identity failure.
Passing connection information to psql with a connection string
A PostgreSQL connection URI can carry the same settings. Quote the whole URI so shell metacharacters such as & are not interpreted. This template deliberately omits the password and prompts for it:
URI components containing reserved characters must be percent-encoded; for example, @ within a component becomes %40. If a library requires a password-bearing URI, load it from protected configuration and avoid logging it.
Local Unix sockets do not use TLS. Loopback TCP in a disposable development environment can have a separately scoped policy, but an unqualified connection's default sslmode=prefer does not verify a remote server's identity. The companion authentication guide explains the server-side rules.
Adjusting a PostgreSQL server's authentication configuration
If you want to modify the rules that dictate how users can authenticate to your PostgreSQL instances, you can do so by modifying your server's configuration. You can find out how to modify PostgreSQL's authentication configuration in this article.
Conclusion
In this guide, we covered PostgreSQL authentication from the client side. We demonstrated how to use the psql command line client to connect to both local and remote database instances using a variety of methods.
Knowing how to connect to various PostgreSQL instances is vital as you start to work the database system. You may run a local PostgreSQL instance for development that doesn't need any special authentication, but your databases in staging and production will almost certainly require authentication. Being able to authenticate in either case will allow you to work well in different environments.
Prisma ORM can help you manage PostgreSQL databases from TypeScript applications. Learn how to add Prisma to an existing project or how to start with Prisma from scratch.
Create a managed Postgres database
Hosted Postgres with automated backups, connection pooling, and Query Insights — ready in seconds.
