配置远程登录
1. 修改PostgreSQL配置文件
编辑 postgresql.conf
文件,该文件通常位于 /etc/postgresql/<版本号>/main/
目录下
以postgresql-14为例,配置文件在/var/lib/pgsql/14/data/postgresql.conf
sudo vim /etc/postgresql/14/main/postgresql.conf
找到 listen_addresses
配置项,并将其设置为您希望PostgreSQL监听的IP地址,或者使用 '*' 让它监听所有地址:
listen_addresses = '*'
2. 修改客户端认证配置文件
编辑 pg_hba.conf
文件,同样位于 /etc/postgresql/14/main/
目录下。需要添加一条规则以允许远程主机连接到数据库:
sudo nano /etc/postgresql/14/main/pg_hba.conf
添加如下格式的行到文件的末尾,以允许特定的IP地址或网段远程访问:
host all all <远程IP地址/网段> md5
或者,允许所有IP地址远程访问(注意安全风险):
host all all 0.0.0.0/0 md5
host all all ::/0 md5
3. 服务器本地登陆postgresql数据库
创建角色,并且给角色设置密码:
postgres=# create user test with password 'Aa1234567890';
CREATE ROLE
修改数据库用户和密码:
postgres=# alter user test with password '558996';
ALTER ROLE
指定字符集创建数据库testdb1,并且授权给testwjw
postgres=# create database testdb1 with encoding='utf8' owner=testwjw;
CREATE DATABASE
授权:
postgres=# grant all privileges on database testdb1 to testwjw;
GRANT
配置管理员用户远程登录
postgresql数据库的默认用户是postgres,PostgreSQL数据库创建一个postgres用户作为数据库的管理员,密码随机,所以需要修改密码,方式如下
ALTER USER postgres WITH PASSWORD 'postgres';
注意:
密码postgres要用引号引起来
命令最后有分号
步骤三:退出PostgreSQL客户端 \q
重启postgres使其生效。
systemctl restart postgresql-14