How do I connect to PostgreSQL with psql and verify the database?
psql is PostgreSQL’s interactive command-line client. Specify the intended host, port, user and database so that environment defaults do not select the wrong target. The example connects to PostgreSQL on the same server; database authentication remains separate from the SSH account used to reach that server.
Before you start
- An authorised database account and the intended database name.
- The actual local PostgreSQL port.
Instructions
1. Open an explicit connection
Replace the example account and database. -X prevents psql startup files from changing this diagnostic session, and -W requests an interactive password prompt.
psql -X -h 127.0.0.1 -p 5432 -U appuser -d appdb -WConnects to the example local TCP listener without placing the password in the command line.
2. Verify the session
Run these commands after the psql prompt appears. The connection report includes transport information; the SQL confirms the active database and role.
\conninfo
SELECT current_database(), current_user, inet_server_addr(), inet_server_port();Reads the current connection context without selecting application records.
3. Return to the operating-system shell
Leave psql before issuing Linux commands. When automating later, use a protected credential mechanism and deliberately check both connection and query failures.
\qExits the psql session.
Check the result
- The authenticated role, database and endpoint match the intended environment.
Troubleshooting
- Peer authentication failed
- A UNIX-socket connection may be using peer authentication. Check the intended transport and the applicable pg_hba.conf rule with the database administrator.
- psql is much older than the server
- Use a supported compatible client, particularly for backslash metadata commands.
Official references
Use the documentation for your installed version when a flag, service name or platform feature differs.
