PostgreSQL创建用户并配置远程连接

1,657 阅读1分钟

默认情况下安装的PostgreSQL无法远程访问

#切换到postgres用户登录

root@node1:~# su - postgres
postgres@node1:~$ psql
psql (15.3 (Debian 15.3-0+deb12u1))
Type "help" for help.

postgres=# 
# 创建新用户

postgres=# create user test with password '123456';
CREATE ROLE

# 创建属于test用户的数据库

postgres=# create database testdb owner test;
CREATE DATABASE

# 将testdb数据库的所有权限都赋予test

postgres=# grant all privileges on database testdb to test;
GRANT

开启远程访问

# 编辑配置文件postgresql.conf 

vim /etc/postgresql/15/main/postgresql.conf 

#添加/修改如下内容:在所有IP地址上监听,从而允许远程连接到数据库服务器:

listening_address: '*'
# 编辑配置文件pg_hba.conf,该文件是一个黑白名单访问控制文件,可以控制允许那些ip地址的机器访问数据库

vim /etc/postgresql/15/main/pg_hba.conf 

# 添加/修改:允许任意用户从任意机器上以密码方式访问数据库,把下行添加为第一条规则:

host    all             all             0.0.0.0/0               md5
# 重启postgresql
systemctl start postgresql
# 测试postgresql

my-ubuntu:~$ psql -h 172.16.183.134 testdb -U test -W
Password: 
psql (15.3 (Ubuntu 15.3-1.pgdg22.04+1))
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off)
Type "help" for help.

testdb=> 
testdb=> 
testdb=> 
testdb=> \q

参考文章

blog.csdn.net/Rong_Toa/ar…