Install and secure PostgreSQL 14 on Ubuntu 22.04
26/10/2023 - 1 phút
Step 1: Install PostgreSQL 14 on Ubuntu 22.04.2 LTS
Open the terminal and update the package list:
sudo apt update
Install PostgreSQL 14 with the following command:
sudo apt install postgresql-14 -y
PostgreSQL will automatically start after installation. You can check its status with the command:
sudo systemctl status postgresql
Step 2: Secure PostgreSQL
Start by setting a password for the “postgres” user account (default):
sudo passwd postgres
Switch to the “postgres” account and open the PostgreSQL shell:
sudo -i -u postgres psql
Set a password for the “postgres” account:
\password postgres
Enter the new password and confirm.
Exit the PostgreSQL shell:
\q exit
Step 3: Create Database and User
Log in to PostgreSQL with the “postgres” account:
sudo -i -u postgres
Open the PostgreSQL shell:
psql
Create a database (example: “mydatabase”):
CREATE DATABASE mydatabase;
Create a user (example: “myuser”) and set a password:
CREATE USER myuser WITH PASSWORD 'mypassword';
Assign privileges to the user to access and manage the database:
GRANT ALL PRIVILEGES ON DATABASE mydatabase TO myuser;
End the session and exit:
\q exit
Step 4: Check the connection
psql -h localhost -U myuser -d mydatabase
Step 5: Configure security
Open the configuration file:
sudo nano /etc/postgresql/14/main/pg_hba.conf
Change the authentication method of all connections to “md5”:
local all all md5 host all all
Restart PostgreSQL:
sudo systemctl restart postgresql
Thank you for reading this article.