CentOS7安装PostgreSQL9.6数据库操作步骤

1,099 阅读1分钟
安装环境
  • 操作系统

    [root@localhost ~]# cat /etc/redhat-release 
    CentOS Linux release 7.6.1810 (Core) 
    
  • 数据库版本 PostgreSQL9.6

  • 官方安装地址

安装
  • 安装rpm

    yum install https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm
    
  • 安装客户端

    yum install postgresql96
    
  • 安装服务端

    yum install postgresql96-server
    
  • 初始化数据库

    /usr/pgsql-9.6/bin/postgresql96-setup initdb
    
  • 设置开机自启

    systemctl enable postgresql-9.6
    
  • 启动数据库

    systemctl start postgresql-9.6
    
  • 重启数据库

    systemctl restart postgresql-9.6
    
  • 停止数据库

    systemctl stop postgresql-9.6
    
  • 数据库安装完成并启动

    [root@localhost ~]# netstat -ntlp |grep 5432       
    tcp        0      0 127.0.0.1:5432          0.0.0.0:*               LISTEN      7251/postmaster     
    tcp6       0      0 ::1:5432                :::*                    LISTEN      7251/postmaster 
    

    PostgreSQL安装完成后,会建立‘postgres’用户,用于执行PostgreSQL,数据库中也会建立postgres用户,密码默自动生成

  • 查看版本

    [root@localhost ~]# psql --version
    psql (PostgreSQL) 9.6.16
    
  • 修改postgres密码

    #切换服务器用户到postgres
    [root@localhost ~]# su - postgres  
    #登录数据库
    -bash-4.2$ psql -U postgres
    psql (9.6.16)
    Type "help" for help.
    #修改postgres密码为123456
    postgres=#  ALTER USER postgres WITH PASSWORD '123456';
    ALTER ROLE
    #退出数据库
    postgres-# \q
    
  • 开启远程访问

    vim /var/lib/pgsql/9.6/data/postgresql.conf
    

    将修改#listen_addresses = 'localhost' 为 listen_addresses='*'

  • 信任远程连接

    vim /var/lib/pgsql/9.6/data/pg_hba.conf 
    

    修改配置文件:

    # IPv4 local connections:
    #host    all             all             127.0.0.1/32            ident
    host    all             all             0.0.0.0/0               md5
    
开放防火墙
  • 方式一:服务方式开启防火墙 由于CentOS防火墙内置PostgreSQL服务,可以采用服务方式开放PostgreSQL 开放PostgreSQL服务
     firewall-cmd --add-service=postgresql --permanent  
    
  • 方式二:开放端口5432(可修改)
    firewall-cmd --permanent --zone=public --add-port=5432/tcp
    
  • 方式三:指定IP访问端口5432
    firewall-cmd --permanent --remove-rich-rule="rule family="ipv4" source address="192.168.47.1" port protocol="tcp" port="5432" accept"
    
  • 重载防火墙
      firewall-cmd --reload