Install Postgres and connect with psql on Ubuntu or Docker
Install Postgres either by running the official Docker image with a named volume or with apt, then open a psql session to list, create and enter databases.
- Updated Nov 27, 2026
- Markdown
Run a Postgres server two ways, connect with psql, and create and inspect a database.
- An Ubuntu or Debian server with sudo, or Docker installed
PostgreSQL is a database server that your apps talk to over a socket or TCP port 5432, and psql is its command-line client. You can run the server from the official Docker image or install it with apt. Both give you the same engine. Pick Docker when the rest of your stack is containers, and apt when you want a plain system service.
How it works#
A Postgres server is one main process that manages one or more databases inside a data directory (the cluster). Clients connect, authenticate as a role, and pick a database. Three things decide whether a connection is allowed:
listen_addressesinpostgresql.confsets which network interfaces the server accepts connections on. The default on a fresh apt install islocalhostonly.pg_hba.confis the host-based authentication file. Each line says which connection type, database, role and source address may connect, and which method to use.- The role must exist and have the
LOGINattribute.
The two methods you meet first are peer and scram-sha-256. Peer is used for local Unix socket connections: the server asks the kernel which Linux user is on the other end and lets that user in as the role with the same name. No password is involved. Over TCP, Debian and Ubuntu use scram-sha-256, which checks a password. That is why sudo -u postgres psql works with no password but psql -h 127.0.0.1 -U postgres asks for one.
Step 1: Run Postgres in Docker#
If you are new to containers, start with run your first container. Then:
docker volume create pgdata
docker run -d --name pg \
-e POSTGRES_PASSWORD=change-me \
-v pgdata:/var/lib/postgresql/data \
-p 127.0.0.1:5432:5432 \
--restart unless-stopped \
postgres:16Replace change-me with a long random password. The image reads POSTGRES_PASSWORD only when it creates a new data directory, so changing it later does not change the stored password. The named volume keeps the data when the container is removed (see Docker volumes and persistent data). The 127.0.0.1: prefix on the port means only the host can connect. A bare -p 5432:5432 publishes to every interface, and Docker bypasses ufw rules for published ports, so avoid it (see publish container ports safely).
Pin a major version in the tag (postgres:16) instead of using latest, because a major upgrade is not automatic (see upgrade Postgres to a new major version).
Connect from inside the container:
docker exec -it pg psql -U postgresStep 2: Or install with apt#
sudo apt update
sudo apt install postgresql
systemctl status postgresql
sudo -u postgres psqlThe postgresql package is a meta package that installs the server version your Ubuntu or Debian release ships. The service is managed by systemd, and systemctl status postgresql should show it as active. On Debian-based systems the cluster lives under /etc/postgresql/<version>/main/ for config and /var/lib/postgresql/<version>/main/ for data. Find the exact config paths from inside psql:
SHOW config_file;
SHOW hba_file;
SHOW data_directory;Step 3: Learn the psql basics#
Meta-commands start with a backslash and do not need a semicolon. SQL does.
| Command | What it does |
|---|---|
\l | List databases |
\c name | Connect to database name |
\dt | List tables in the current database |
\du | List roles |
\? | Show all meta-commands |
\q | Quit |
To connect to a specific database over TCP with a password:
psql -h 127.0.0.1 -p 5432 -U postgres -d shopYou can also run one statement and exit: sudo -u postgres psql -c "SELECT version();".
Step 4: Control who can connect#
To let another machine reach the server, you need both settings. Edit postgresql.conf:
listen_addresses = 'localhost,203.0.113.10'Then add a line to pg_hba.conf that allows only the app host:
host shop app 203.0.113.11/32 scram-sha-256Reload with sudo systemctl reload postgresql (a listen_addresses change needs restart). Allow the port only from that host in your firewall as well. Most single-server setups never need this: keep Postgres on localhost or a private Docker network and let the app connect from the same machine.
Check it worked#
\linside psql listspostgres,template0andtemplate1, plus your own databases.SELECT version();prints the server version.- Docker:
docker psshows thepgcontainer asUp, anddocker logs pgends withdatabase system is ready to accept connections. - apt:
sudo ss -ltnp | grep 5432shows the listener on127.0.0.1:5432(see find what is using a port).
Edge cases and gotchas#
- The password variable only works once.
POSTGRES_PASSWORDis applied when the data directory is empty. If the volume already has data, the stored role passwords win, and changing the variable does nothing. - Pasting the volume path wrongly loses data. Mount the volume on
/var/lib/postgresql/dataas the image documents for the version you pin. Check the image page for any path change in newer major versions before you upgrade. - Published ports ignore ufw. Docker writes its own firewall rules, so
-p 5432:5432can expose the database even with ufw denying it. Bind to127.0.0.1. postgresis a Linux user and a role. Do not set a password for the Linux user or run your app as it. Create a separate role for the app (next lessons).- Semicolons. A statement without
;just waits on a continuation prompt likepostgres-#. Type;or press Ctrl+C to cancel. - Two clusters on one port. If you install apt Postgres while a container already publishes 5432, one of them fails to bind. Use a different host port for one of them.
Troubleshooting#
| Symptom | Likely cause | Fix |
|---|---|---|
psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory | Server is not running, or you are inside a container with no server | sudo systemctl start postgresql, or use docker exec |
FATAL: Peer authentication failed for user "postgres" | peer rule on the socket and your Linux user is not postgres | Use sudo -u postgres psql |
FATAL: password authentication failed for user "postgres" | Wrong password, or the volume had an older password | Reset it with ALTER ROLE postgres PASSWORD '...'; from a working session |
psql: error: connection to server at "127.0.0.1", port 5432 failed: Connection refused | Server down, or published on a different port | Check docker ps or systemctl status postgresql |
FATAL: no pg_hba.conf entry for host "203.0.113.11", user "app", database "shop", SSL encryption | No matching line in pg_hba.conf | Add a host line for that address and reload |
docker: Error response from daemon: ... Bind for 127.0.0.1:5432 failed: port is already allocated | Another Postgres holds the port | Stop it or publish 127.0.0.1:5433:5432 |
Error: Database is uninitialized and superuser password is not specified. | POSTGRES_PASSWORD missing on first start | Recreate with the variable set |
CREATE DATABASE cannot run inside a transaction block | Run inside a BEGIN block | End the transaction first |
Quick reference#
# Docker
docker volume create pgdata
docker run -d --name pg -e POSTGRES_PASSWORD=change-me \
-v pgdata:/var/lib/postgresql/data -p 127.0.0.1:5432:5432 postgres:16
docker exec -it pg psql -U postgres
# apt
sudo apt install postgresql
sudo -u postgres psql
psql -h 127.0.0.1 -U app -d shop
# in psql
\l \c shop \dt \du \? \q
SHOW hba_file; SHOW listen_addresses;Related lessons#
- Postgres roles and permissions: give your app its own limited login.
- Database connection strings explained: turn host, user and database into a URL.
- Docker volumes and persistent data: why the named volume matters.
- Back up a Postgres database in Docker: protect what you just created.
- Self-hosted Postgres in Docker, connect your app: an app-side walkthrough.
Next#
Continue with Postgres roles and permissions to stop your app running as the superuser.
Try it: Connect to Postgres and make a database
Open psql as the postgres user, list databases, create one, enter it and look for tables.
Want a real machine? Free browser labs: Killercoda
Check what you learned
Frequently asked questions
How do I install PostgreSQL on Ubuntu?
Run sudo apt update, then sudo apt install postgresql. The service starts on its own, and you connect with sudo -u postgres psql.
How do I run Postgres in Docker?
Run the postgres image with POSTGRES_PASSWORD set, a named volume on /var/lib/postgresql/data, and a port published on 127.0.0.1 only if you need host access.
What is the default Postgres port?
Postgres listens on TCP port 5432 by default. Keep it bound to localhost or a private network unless you have a firewall rule and a reason.
Why does psql say peer authentication failed?
The pg_hba.conf rule for local socket connections uses peer, so your Linux username must match the database role. Use sudo -u postgres psql or connect over TCP with a password.
Sources
Keep going: guides and tutorials
- Self-Hosted Postgres in Docker: Connect It to Your App Run Postgres in Docker as its own resource with its own volume, connect your app with one command, and read the reachability badge before a timeout hits.
- Manage Secrets Self-Hosted: Env Vars and Master Key Rotation Set env vars and encrypted secrets on a self-hosted server, apply changes safely, and rotate the master key with no downtime without locking yourself out.