PostgreSQL trên Ubuntu

1. Cài PostgreSQL

sudo apt update
sudo apt upgrade -y
sudo apt install postgresql postgresql-contrib -y
   -- postgresql: database server
   -- postgresql-contrib: các extension hữu ích
sudo systemctl status postgresql -- Kiểm tra trạng thái PostgreSQL

2. Đăng nhập vào PostgreSQL

2.1 PostgreSQL tạo user mặc định là postgres.
sudo -i -u postgres
psql
-- Nếu thành công bạn sẽ thấy:
postgres=#
-- Thoát:
\q
2.2 Tạo database và user mới (khuyến nghị)
-- Tạo user:
CREATE USER username WITH PASSWORD 'password';

-- Tạo database:
CREATE DATABASE dbname;

-- Tạo và Gán database cho user:
CREATE DATABASE mydb OWNER myuser;

-- Đổi mật khẩu:
ALTER USER username WITH PASSWORD 'new_password';
2.3 Kiểm tra version
psql --version

3. Đăng nhập từ Terminal

Cú pháp:

psql -U username -d database_name -h localhost -W

Ví dụ:

psql -U myuser -d mydb -h localhost -W

Giải thích:

  • -U : username PostgreSQL
  • -d : database muốn truy cập
  • -h : host (localhost)
  • -W : yêu cầu nhập password

Sau đó nhập password của user.

4. Cấp quyền (nếu cần)

-- Cho phép user tạo database:
ALTER USER devuser CREATEDB;

-- Cho phép quyền admin (chỉ dùng khi thật sự cần):
ALTER USER devuser WITH SUPERUSER;

-- Kiểm tra danh sách user:
\du

-- Đăng nhập bằng user mới
psql -U devuser -d devdb -h localhost -W
6. Kiểm tra Post bằng cách Kiểm tra trong file cấu hình (chuẩn nhất)

Mở file: sudo nano /etc/postgresql/*/main/postgresql.conf

Tìm dòng: port = 5432

7. Nếu bạn muốn login PostgreSQL bằng password từ localhost, có thể cần chỉnh file
/etc/postgresql/<version>/main/pg_hba.conf

đổi: peer => thành: md5

Sau đó restart: sudo systemctl restart postgresql

-- Nếu không login được: đổi md5 sang trust
-- Restart: sudo systemctl restart postgresql
-- đổi mật khẩu: ALTER USER postgres WITH PASSWORD 'newpassword';
-- đổi lại từ trust về md5 để đảm bảo bảo mật
-- Restart: sudo systemctl restart postgresql

Hãy bình luận đầu tiên

Để lại một phản hồi

Thư điện tử của bạn sẽ không được hiện thị công khai.


*