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

URL: https://levelrail.com/learn/databases/install-postgres-and-connect-with-psql/
Updated: 2026-11-27

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](https://levelrail.com/learn/docker/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](https://levelrail.com/learn/glossary/#volume)) keeps the data when the container is removed (see [Docker volumes and persistent data](https://levelrail.com/learn/docker/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](https://levelrail.com/learn/docker/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](https://levelrail.com/learn/databases/upgrade-postgres-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](https://levelrail.com/learn/glossary/#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.

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

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

```
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-256
```

Reload with `sudo systemctl reload postgresql` (a `listen_addresses` change needs `restart`). Allow the port only from that host in your [firewall](https://levelrail.com/learn/glossary/#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](https://levelrail.com/learn/server-basics/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

| 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

```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;
```

## Related lessons

- [Postgres roles and permissions](https://levelrail.com/learn/databases/postgres-roles-and-permissions/)): give your app its own limited login.
- [Database connection strings explained](https://levelrail.com/learn/databases/database-connection-strings-explained/)): turn host, user and database into a URL.
- [Docker volumes and persistent data](https://levelrail.com/learn/docker/docker-volumes-and-persistent-data/)): why the named volume matters.
- [Back up a Postgres database in Docker](https://levelrail.com/learn/deploy-operate/back-up-a-postgres-database-in-docker/)): protect what you just created.
- [Self-hosted Postgres in Docker, connect your app](https://levelrail.com/blog/self-hosted-postgres-docker-connect-app/)): an app-side walkthrough.

## Next

Continue with [Postgres roles and permissions](https://levelrail.com/learn/databases/postgres-roles-and-permissions/)) to stop your app running as the superuser.

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

- [PostgreSQL documentation, psql](https://www.postgresql.org/docs/current/app-psql.html)
- [PostgreSQL documentation, client authentication](https://www.postgresql.org/docs/current/client-authentication.html)
