Hướng dẫn cài đặt PostgreSQL trên Linux

PostgreSQL là một hệ thống quản lý cơ sở dữ liệu quan hệ đối tượng (ORDBMS) mã nguồn mở, mạnh mẽ và có nhiều tính năng. Nó hỗ trợ hầu hết các chuẩn SQL và cung cấp các tính năng hiện đại như truy vấn phức tạp, khóa ngoại, trigger, view, tính toàn vẹn giao dịch và kiểm soát truy cập đa phiên bản. PostgreSQL cũng có khả năng mở rộng cao thông qua việc thêm các kiểu dữ liệu, hàm, toán tử, hàm tổng hợp, phương thức đánh chỉ mục và ngôn ngữ thủ tục mới. Giấy phép sử dụng linh hoạt cho phép người dùng miễn phí sử dụng, sửa đổi và phân phối PostgreSQL cho bất kỳ mục đích nào.

Các bước cài đặt

  1. Tải về PostgreSQL: Truy cập trang tải về chính thức của EnterpriseDB để tải xuống phiên bản phù hợp. Sau đó, tải tệp đã tải lên máy chủ vào thư mục /home và giải nén, bạn sẽ có thư mục pgsql.
  2. Tạo người dùng và đặt mật khẩu:
    
    [root@localhost home]# useradd postgres
    [root@localhost home]# passwd postgres
    Changing password for user postgres.
    New password:
    BAD PASSWORD: The password contains the username in some form.
    Retype new password:
    passwd: all authentication tokens updated successfully.
            
    Lưu ý: Mật khẩu này là để đăng nhập vào hệ thống Linux cho người dùng postgres, không phải là mật khẩu cho máy chủ PostgreSQL.
  3. Tạo thư mục dữ liệu và cấp quyền:
    
    # Đang ở thư mục /home
    [root@localhost home]# pwd
    /home
    
    # Tạo thư mục /home/pgsql/pgsql_data
    [root@localhost home]# mkdir pgsql/pgsql_data
    
    # Cấp quyền sở hữu thư mục pgsql_data cho người dùng postgres
    [root@localhost home]# chown postgres:postgres pgsql/pgsql_data
            
  4. Khởi tạo cơ sở dữ liệu: Chuyển sang người dùng postgres để thực hiện các thao tác. PostgreSQL mặc định sử dụng postgres làm người dùng. Sử dụng lệnh su - postgres để chuyển đổi.
    
    # Chuyển sang người dùng postgres
    [root@localhost home]# su postgres
    
    # Kiểm tra thư mục hiện tại
    -bash-4.2$ pwd
    /home
    
    # Khởi tạo cơ sở dữ liệu
    -bash-4.2$ /home/pgsql/bin/initdb -D /home/pgsql/pgsql_data
    The files belonging to this database system will be owned by user "postgres".
    This user must also own the server process.
    
    The database cluster will be initialized with locale "zh_CN.UTF-8".
    The default database encoding has accordingly been set to "UTF8".
    initdb: could not find suitable text search configuration for locale "zh_CN.UTF-8"
    The default text search configuration will be set to "simple".
    
    Data page checksums are disabled.
    
    fixing permissions on existing directory /home/pgsql/pgsql_data ... ok
    creating subdirectories ... ok
    selecting default max_connections ... 100
    selecting default shared_buffers ... 128MB
    selecting default timezone ... Asia/Shanghai
    selecting dynamic shared memory implementation ... posix
    creating configuration files ... ok
    running bootstrap script ... ok
    performing post-bootstrap initialization ... ok
    syncing data to disk ... ok
    
    WARNING: enabling "trust" authentication for local connections
    You can change this by editing pg_hba.conf or using the option -A, or
    --auth-local and --host, the next time you run initdb.
    
    Success. You can now start the database server using:
    
        /home/pgsql/bin/pg_ctl -D /home/pgsql/pgsql_data -l logfile start
            
  5. Khởi động máy chủ cơ sở dữ liệu: Lệnh khởi động được hiển thị ở cuối quá trình khởi tạo.
    
    -bash-4.2$ /home/pgsql/bin/pg_ctl -D /home/pgsql/pgsql_data -l /home/pgsql/logfile start
    waiting for server to start.... done
    server started
            
    Sau khi khởi động, bạn có thể kiểm tra các tiến trình PostgreSQL bằng lệnh:
    
    -bash-4.2$ ps -ef | grep postgres
    root     20480  4206  0 16:10 pts/0    00:00:00 su - postgres
    postgres 20481 20480  0 16:10 pts/0    00:00:00 -bash
    postgres 20544     1  0 16:16 pts/0    00:00:00 /home/pgsql/bin/postgres -D /home/pgsql/pgsql_data
    postgres 20546 20544  0 16:16 ?        00:00:00 postgres: checkpointer process
    postgres 20547 20544  0 16:16 ?        00:00:00 postgres: writer process
    postgres 20548 20544  0 16:16 ?        00:00:00 postgres: wal writer process
    postgres 20549 20544  0 16:16 ?        00:00:00 postgres: autovacuum launcher process
    postgres 20550 20544  0 16:16 ?        00:00:00 postgres: stats collector process
    postgres 20551 20544  0 16:16 ?        00:00:00 postgres: bgworker: logical replication launcher
    postgres 20552 20481  0 16:16 pts/0    00:00:00 ps -ef
    postgres 20553 20481  0 16:16 pts/0    00:00:00 grep --color=auto postgres
            
    Cổng mặc định của PostgreSQL là 5432.
    
    -bash-4.2$ netstat -tunlp | grep 5432
    (Not all processes could be identified, non-owned process info
     will not be shown, you would have to be root to see it all.)
    tcp        0      0 127.0.0.1:5432          0.0.0.0:*               LISTEN      20544/postgres
    tcp6       0      0 ::1:5432                :::*                    LISTEN      20544/postgres
            
  6. Cho phép truy cập từ xa: Chỉnh sửa tệp cấu hình postgresql.conf nằm trong thư mục dữ liệu.
    
    # Tìm thư mục dữ liệu
    [root@localhost pgsql_data]# pwd
    /home/pgsql/pgsql_data
    
    # Liệt kê các tệp cấu hình
    [root@localhost pgsql_data]# ls
    base    pg_commit_ts  pg_hba.conf    pg_logical    pg_notify    pg_serial     pg_stat      pg_subtrans  pg_twophase  pg_wal   postgresql.auto.conf  postmaster.opts
    global  pg_dynshmem   pg_ident.conf  pg_multixact  pg_replslot  pg_snapshots  pg_stat_tmp  pg_tblspc    PG_VERSION   pg_xact  postgresql.conf       postmaster.pid
    
    # Mở tệp postgresql.conf bằng trình soạn thảo văn bản
    [root@localhost pgsql_data]# vi postgresql.conf
            
    Bỏ dấu thăng (#) ở dòng listen_addresses và thay đổi giá trị từ localhost thành *. Sau đó, khởi động lại máy chủ:
    
    /home/pgsql/bin/pg_ctl -D /home/pgsql/pgsql_data -l /home/pgsql/logfile restart
            
    Kiểm tra lại cổng:
    
    # Trước khi thay đổi (chỉ lắng nghe trên 127.0.0.1)
    [root@localhost pgsql_data]# netstat -tunlp | grep 5432
    tcp        0      0 127.0.0.1:5432          0.0.0.0:*               LISTEN      20544/postgres
    tcp6       0      0 ::1:5432                :::*                    LISTEN      20544/postgres
    
    # Sau khi thay đổi (lắng nghe trên tất cả các địa chỉ)
    [root@localhost pgsql_data]# netstat -tunlp | grep 5432
    tcp        0      0 0.0.0.0:5432            0.0.0.0:*               LISTEN      20595/postgres
    tcp6       0      0 :::5432                 :::*                    LISTEN      20595/postgres
            
  7. Kết nối tới cơ sở dữ liệu:
    
    [root@localhost bin]# /home/pgsql/bin/psql -h 127.0.0.1 -d postgres -U postgres -p 5432
    psql.bin (10.10)
    Type "help" for help.
    
    postgres=#
            
    Trong đó:
    • -h: địa chỉ máy chủ (mặc định là 127.0.0.1).
    • -d: tên cơ sở dữ liệu cần kết nối (mặc định là postgres).
    • -U: tên người dùng (mặc định là người dùng hiện tại).
    • -p: số cổng (mặc định là 5432).
    Để xem danh sách các cơ sở dữ liệu hiện có, sử dụng lệnh \l:
    
    postgres=# \l
                                      List of databases
       Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges
    -----------+----------+----------+-------------+-------------+-----------------------
     postgres  | postgres | UTF8     | zh_CN.UTF-8 | zh_CN.UTF-8 |
     template0 | postgres | UTF8     | zh_CN.UTF-8 | zh_CN.UTF-8 | =c/postgres          +
               |          |          |             |             | postgres=CTc/postgres
     template1 | postgres | UTF8     | zh_CN.UTF-8 | zh_CN.UTF-8 | =c/postgres          +
               |          |          |             |             | postgres=CTc/postgres
    (3 rows)
            
    Để tạo một cơ sở dữ liệu mới, ví dụ test, với người dùng postgres và mã hóa UTF-8:
    
    postgres=# CREATE DATABASE test WITH OWNER=postgres ENCODING='UTF-8';
    CREATE DATABASE
            
    Để chuyển sang cơ sở dữ liệu test, sử dụng lệnh \c test. Để xem danh sách các bảng trong cơ sở dữ liệu hiện tại, sử dụng lệnh \d.
    
    # Xem danh sách cơ sở dữ liệu sau khi tạo
    postgres=# \l
                                      List of databases
       Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges
    -----------+----------+----------+-------------+-------------+-----------------------
     postgres  | postgres | UTF8     | zh_CN.UTF-8 | zh_CN.UTF-8 |
     template0 | postgres | UTF8     | zh_CN.UTF-8 | zh_CN.UTF-8 | =c/postgres          +
               |          |          |             |             | postgres=CTc/postgres
     template1 | postgres | UTF8     | zh_CN.UTF-8 | zh_CN.UTF-8 | =c/postgres          +
               |          |          |             |             | postgres=CTc/postgres
     test      | postgres | UTF8     | zh_CN.UTF-8 | zh_CN.UTF-8 |
    (4 rows)
    
    # Chuyển sang cơ sở dữ liệu test
    postgres=# \c test
    You are now connected to database "test" as user "postgres".
    
    # Xem bảng trong cơ sở dữ liệu test (hiện chưa có)
    test=# \d
    Did not find any relations.
            
    Tạo bảng:
    
    # Tạo bảng student
    test=# CREATE TABLE student (
    test(#   id integer NOT NULL,
    test(#   name character(32),
    test(#   number char(5),
    test(#   CONSTRAINT student_pkey PRIMARY KEY (id)
    test(# );
    CREATE TABLE
    
    # Xem cấu trúc bảng student
    test=# \d student
                     Table "public.student"
     Column |     Type      | Collation | Nullable | Default
    --------+---------------+-----------+----------+---------
     id     | integer       |           | not null |
     name   | character(32) |           |          |
     number | character(5)  |           |          |
    Indexes:
        "student_pkey" PRIMARY KEY, btree (id)
    
    # Chèn dữ liệu vào bảng student
    test=# INSERT INTO student (id,name,number) VALUES (1,'Zhang San','1023');
    INSERT 0 1
    
    # Xem dữ liệu đã chèn
    test=# SELECT * FROM student WHERE id=1;
     id |     name      | number
    ----+---------------+--------
      1 | Zhang San     | 1023
    (1 row)
    
    # Thoát khỏi psql
    test=# \q
    [root@localhost bin]#
            

Thẻ: PostgreSQL linux Database Installation sql

Đăng vào ngày 24 tháng 8 lúc 09:23