环境

  • CentOS 7
  • PostgreSQL 10.10

安装

  • 安装 yum 源
    1
    2
    3
    4
    5
    6
    7
    8
    
    yum install https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm
    # 或者从清华镜像站下载
    yum install https://mirrors.tuna.tsinghua.edu.cn/postgresql/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm
    # 可以更换成清华镜像站地址
    sed -i 's,download.postgresql.org/pub,mirrors.tuna.tsinghua.edu.cn/postgresql,' /etc/yum.repos.d/pgdg-redhat-all.repo
    # 更新 yum 缓存
    yum clean all
    yum makecache fast
    
  • 安装 postgresql-server
    1
    
    yum install postgresql10-server
    
  • 初始化数据库
    1
    
    /usr/pgsql-10/bin/postgresql-10-setup initdb
    
  • 启动数据库
    1
    
    systemctl start postgresql-10
    

配置 postgresql.conf

  • 监听本机全部地址
    1
    
    clisten_addresses = '*'
    

配置 pg_hba.conf

  • 配置同网段客户端可通过 pguser1 使用密码登陆 pgdb1
    1
    
    echo 'host pgdb1 pguser1 samenet md5' >> pg_hba.conf
    
  • 配置任何客户端可通过任何用户使用密码登陆任何数据库
    1
    
    echo 'host all all all md5' >> pg_hba.conf
    

简单使用

  • 登陆数据库
    1
    2
    
    su - postgres
    psql -U postgres
    
  • 简单操作
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    
    -- 修改 postgres 用户的默认密码
    alter user postgres with password '123456';
    -- 创建新用户 pguser1
    create user pguser1 with password '123456';
    -- 创建数据库 pgdb1
    create database pgdb1 owner pguser1 encoding utf8;
    -- 授权
    grant all on database pgdb1 to pguser1;
    -- 查看系统操作帮助
    \?
    -- 查看 sql 语句操作帮助
    \h
    -- 查看建库语句操作
    \h create database
    -- 退出数据库
    \q
    

迁移数据库目录

  • 停止数据库 postgresql
    1
    
    systemctl stop postgresql-10
    
  • 移动数据库目录
    1
    2
    3
    
    mkdir -p /data/pgsql/10
    mv /var/lib/pgsql/10/data /data/pgsql/10/
    chown -R postgres.postgres /data/pgsql
    
  • 修改 service 文件
    1
    2
    
    sed -i 's,/var/lib/pgsql/10,/data/pgsql/10,' /usr/lib/systemd/system/postgresql-10.service
    systemctl daemon-reload
    
  • 启动数据库
    1
    
    systemctl start postgresql-10