PostgreSQL on Ubuntu: install it, connect, make a database
Install PostgreSQL on Ubuntu the way a server does, connect with psql, and make a role and a database for your own project.
Install PostgreSQL on Ubuntu the way a server does, connect with psql, and make a role and a database for your own project.
In plain words
A database server is a very organised filing clerk. You do not rummage through the drawers yourself: you tell the clerk what to file and what to fetch, and the clerk keeps everything in order and never forgets.
Try it yourself
Install it from the Ubuntu archive. On a normal server the installer also starts it:
sudo apt install -y postgresql
pg_lsclusters
sudo -u postgres psql -c 'select version();'
sudo -u postgres psql -c '\l'
pg_lsclusters should show one cluster, 16 main, online. PostgreSQL has its own Linux user, postgres, and the built-in administrator role of the same name; sudo -u postgres runs a command as that user, and over the local socket no password is needed because PostgreSQL recognises the Linux user. Now make a role and a database for your own project:
sudo -u postgres psql -c "create role app login password 'app'"
sudo -u postgres psql -c "create database appdb owner app"
PGPASSWORD=app psql -h localhost -U app -d appdb -c 'select current_user'
The last command connects over the network address localhost with a password, which is how your Python program will connect.
A step further
Where things are: settings in /etc/postgresql/16/main/, data in /var/lib/postgresql/16/main/, the log in /var/log/postgresql/. The file pg_hba.conf decides who may connect how: by local socket (peer, your Linux user) or by password over the network. On a server managed by systemd, systemctl status postgresql shows whether the service is running.
The password app is fine for a training database that only listens on your own machine. It must never be a real password.
How it works in real projects
Production databases are backed up (pg_dump), reachable only from the servers that need them, and every program gets its own role with only the rights it needs. Nobody uses the all-powerful postgres role for an application.