CentOS 7 安装最新版PostgreSQL

以下操作均在root账号下操作.

一、安装

  1. 查看本机CentOS的版本: cat /etc/redhat-release

  2. 查看最新版本的postgresql yum源

    在PostgreSQL官方的yum找到最新稳定版的yum源,复制rpm的链接。当前的最新版本为9.6。https://yum.postgresql.org/

  3. 导入yum源文件

    rpm -ivh https://download.postgresql.org/pub/repos/yum/9.6/redhat/rhel-7-x86_64/pgdg-centos96-9.6-3.noarch.rpm
    
  4. 通过yum安装最新版的postgresql

    yum -y install postgresql96*
    

    安装后的目录在/usr/pgsql-9.6/

二、配置

  1. 数据库初始化

    /usr/pgsql-9.6/bin/postgresql96-setup initdb
    

    初始化后的数据库目录在/var/lib/pgsql/9.6/data/

  2. 修改服务设置 (根据实际需要去修改),例如修改成监听所有IP地址

    vi /var/lib/pgsql/9.6/data/postgresql.conf
    
    #59行: 表示监听所有IP地址(强烈建议通过防火墙IP白名单控制, 否则有安全隐患) 
    listen_addresses = '*' 
    
    #347行: 指定日志文件的格式为2016-04-01.log这样的日期格式。
    log_filename = 'postgresql-%Y%m%d.log'
    
    #433行: 修改日志输出的格式
    log_line_prefix = '<%t %u %d>'
    
  3. 修改数据库认证模式为md5

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

    将原有的设置全部注释掉,然后增加以下三行内容:

    local   all             postgres                                peer
    local   all             all                                     md5
    host    all             all             0.0.0.0/0               md5
    host    all             all             ::1/128                 md5   
    
  4. 启动服务

    systemctl start postgresql-9.6
    
  5. 设置服务自动启动

    systemctl enable postgresql-9.6
    

三、PostgreSQL的基本使用

切换到postgres账号终端下

su - postgres
  1. createdb命令:创建数据库

    # postgres账号的终端下
    createdb dbtest
    
  2. createuser命令:创建账号

    # postgres账号的终端下
    $ createuser dbuser1
    
  3. 设置/修改DB用户的密码

    # 以postgres账号身份登陆psql终端
    $ psql -U postgres
    

    在psql终端下,通过以下命令修改密码

    postgres=#  ALTER USER dbuser1 encrypted password 'mypass';
    
  4. psql终端下查看数据库

    postgres=# \l
    
  5. 切换数据库

    postgres=# \c 数据库名
    
  6. 修改数据库的拥有者

    postgres=# ALTER DATABASE dbtest OWNER TO dbuser1;
    
  7. 退出psql终端

    postgres=# \q
    
  8. 指定用户名及数据库登陆psql

    $ psql -U dbuser1 dbtest
    
  9. 在其它linux用户下,可以通过sudo命令使用postgres的psql

    #例如,当前登陆的linux账号为deploy,想执行psql
    sudo -u postgres psql -U postgres
    

四、其它设置

  1. 防火墙的设置样例(使用firewalld的情况下):

    #样例一:对指定IP地址完全开放
    firewall-cmd --zone=public --add-rich-rule='rule family="ipv4" source address="xxx.xxx.xxx.xxx" accept' --permanent
    
    #样例二:对指定IP地址开放指定服务(使用自定义zone的方式)
    firewall-cmd --permanent --add-source=xxx.xxx.xxx.0/24 --zone=my_group
    firewall-cmd --permanent --add-service=postgresql --zone=my_group
    firewall-cmd --reload
    
    #样例三:对指定IP地址开放指定端口
    firewall-cmd --permanent --zone=public --add-rich-rule=' \
      rule family="ipv4" \
      source address="xxx.xxx.xxx.xxx/32" \
      port protocol="tcp" port="5432" accept'
    
    #样例四:对所有IP地址开放(危险,不推荐)
    firewall-cmd --zone=public --add-service=postgresql --permanent
    
    #重启firewalld服务
    systemctl restart firewalld
    

五、Postgres的参考资料

Share Comments
comments powered by Disqus