Chapter 9 · Lesson 1 of 8
Databases and data

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.

By the end you will

Run a Postgres server two ways, connect with psql, and create and inspect a database.

Time
20 min
Level
Beginner
Check
4 questions
You need
  • 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_addresses in postgresql.conf sets which network interfaces the server accepts connections on. The default on a fresh apt install is localhost only.
  • pg_hba.conf is 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 LOGIN attribute.

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:

bash
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:16

Replace 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:

bash
docker exec -it pg psql -U postgres

Step 2: Or install with apt#

bash
sudo apt update
sudo apt install postgresql
systemctl status postgresql
sudo -u postgres psql

The 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:

sql
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.

CommandWhat it does
\lList databases
\c nameConnect to database name
\dtList tables in the current database
\duList roles
\?Show all meta-commands
\qQuit

To connect to a specific database over TCP with a password:

bash
psql -h 127.0.0.1 -p 5432 -U postgres -d shop

You 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:

output
listen_addresses = 'localhost,203.0.113.10'

Then add a line to pg_hba.conf that allows only the app host:

output
host  shop  app  203.0.113.11/32  scram-sha-256

Reload 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#

  • \l inside psql lists postgres, template0 and template1, plus your own databases.
  • SELECT version(); prints the server version.
  • Docker: docker ps shows the pg container as Up, and docker logs pg ends with database system is ready to accept connections.
  • apt: sudo ss -ltnp | grep 5432 shows the listener on 127.0.0.1:5432 (see find what is using a port).

Edge cases and gotchas#

  • The password variable only works once. POSTGRES_PASSWORD is 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/data as 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:5432 can expose the database even with ufw denying it. Bind to 127.0.0.1.
  • postgres is 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 like postgres-#. 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#

SymptomLikely causeFix
psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directoryServer is not running, or you are inside a container with no serversudo 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 postgresUse sudo -u postgres psql
FATAL: password authentication failed for user "postgres"Wrong password, or the volume had an older passwordReset it with ALTER ROLE postgres PASSWORD '...'; from a working session
psql: error: connection to server at "127.0.0.1", port 5432 failed: Connection refusedServer down, or published on a different portCheck docker ps or systemctl status postgresql
FATAL: no pg_hba.conf entry for host "203.0.113.11", user "app", database "shop", SSL encryptionNo matching line in pg_hba.confAdd a host line for that address and reload
docker: Error response from daemon: ... Bind for 127.0.0.1:5432 failed: port is already allocatedAnother Postgres holds the portStop it or publish 127.0.0.1:5433:5432
Error: Database is uninitialized and superuser password is not specified.POSTGRES_PASSWORD missing on first startRecreate with the variable set
CREATE DATABASE cannot run inside a transaction blockRun inside a BEGIN blockEnd the transaction first

Quick reference#

bash
# 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;

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.

practice, nothing runs on your machine

Want a real machine? Free browser labs: Killercoda

Check what you learned4 questions
1Why mount a named volume on /var/lib/postgresql/data in the Docker image?
2What does the psql command \c shop do?
3On apt installs, which command opens psql as the superuser role?
4Which publish flag keeps a Docker Postgres reachable only from the host itself?

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

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios