侧边栏壁纸
博主头像
里奥的博客博主等级

行动起来,活在当下

  • 累计撰写 51 篇文章
  • 累计创建 8 个标签
  • 累计收到 2 条评论

目 录CONTENT

文章目录

EC2 Debian 安装 PostgreSQL

里奥
2024-07-16 / 0 评论 / 1 点赞 / 165 阅读 / 4235 字

使用 Apt 安装

配置 Apt repository

# Import the repository signing key:
sudo apt install curl ca-certificates
sudo install -d /usr/share/postgresql-common/pgdg
sudo curl -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc --fail https://www.postgresql.org/media/keys/ACCC4CF8.asc

# Create the repository configuration file:
sudo sh -c 'echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'

# Update the package lists:
sudo apt update

安装

下面的命令是安装最新的版本, 如果你要安装其它的版本需要使用类似 'postgresql-16' 而不是使用 'postgresql'

sudo apt -y install postgresql

启动服务

sudo systemctl start postgresql

查看服务状态

sudo systemctl status postgresql

status.png

服务配置

用户配置

系统用户 (system user) 密码设置, 使用下面的命令修改 PostgreSQL 的系统用户的密码.

sudo passwd postgres

修改好后使用系统用户 postgres 登陆.

su - postgres

登陆上之后, 接下来修改数据库管理员密码

psql -c "ALTER USER postgres WITH PASSWORD 'your-password';"

adminpwd-krhd.png

为 AWS EC2 Linux 上的 PostgreSQL 配置远程连接

为 PostgreSQL 配置远程连接,需要配置两个文件 postgresql.confpg_hba.conf

查找配置文件路径

下面的步骤参考了链接: Postgres find configuration files in linux

  1. 使用 su - postgres 登陆, 如果登录不上可以使用 sudo -i -u postgres 登陆.
  2. 输入 psql 后回车
  3. 查找 postgresql.conf 的路径,用 SHOW config_file;, 输出结果像下面这样
postgres=# SHOW config_file;
               config_file               
-----------------------------------------
 /etc/postgresql/16/main/postgresql.conf
(1 row)
  1. 查找 pg_hba.conf 使用 SHOW hba_file;, 输出结果像下面这样
postgres=# SHOW hba_file;
              hba_file               
-------------------------------------
/etc/postgresql/16/main/pg_hba.conf
(1 row)

修改配置文件

  1. 修改 postgresql.conf
sudo vi /etc/postgresql/16/main/postgresql.conf

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

pgconf.png

  1. 修改 pg_hba.conf
/etc/postgresql/16/main/pg_hba.conf

将下面的配置中的 ip 的值由 127.0.0.1/32 修改为 0.0.0.0/0. 有的配置中用的 md5 加密方式, 最新的 PostgreSQL 使用的是 scram-sha-256 加密, 这里不需要修改它

# IPv4 local connections: 
host    all             all             127.0.0.1/32        scram-sha-256

修改后为

# IPv4 local connections:
host    all             all             0.0.0.0/0            scram-sha-256 

pghbaconf.png 修改完成后记得重新启动 postgresql , 让配置生效

sudo systemctl restart postgresql

EC2 安全组设置

需要在 EC2 的安全组中开放 5432 这个端口.

上面配置完成后就可以远程连接数据库了

参考链接

1

评论区