在腾讯云服务器上安装 PostgreSQL 的步骤如下。假设你使用的是 CentOS 7/8 或 Ubuntu 18.04/20.04/22.04 系统,以下是详细操作流程。
✅ 一、准备工作
-
登录腾讯云服务器
- 使用 SSH 登录你的云服务器:
ssh root@你的公网IP - 建议使用密钥或密码方式登录。
- 使用 SSH 登录你的云服务器:
-
更新系统包
- Ubuntu:
sudo apt update && sudo apt upgrade -y - CentOS:
sudo yum update -y # 或者 CentOS 8+ 使用 dnf sudo dnf update -y
- Ubuntu:
✅ 二、安装 PostgreSQL
方式一:Ubuntu 安装 PostgreSQL
-
安装 PostgreSQL:
sudo apt install postgresql postgresql-contrib -y -
启动并设置开机自启:
sudo systemctl start postgresql sudo systemctl enable postgresql -
检查状态:
sudo systemctl status postgresql
方式二:CentOS 安装 PostgreSQL
-
添加 PostgreSQL 官方 YUM 源(以 PostgreSQL 15 为例):
sudo yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm注意:根据你的 CentOS 版本调整 URL(如 EL-8 或 EL-9)
-
安装 PostgreSQL 15(或其他版本):
sudo yum install -y postgresql15-server postgresql15 -
初始化数据库(CentOS 需要):
sudo /usr/pgsql-15/bin/postgresql-15-setup initdb -
启动并设置开机自启:
sudo systemctl start postgresql-15 sudo systemctl enable postgresql-15 -
检查状态:
sudo systemctl status postgresql-15
✅ 三、配置 PostgreSQL
1. 切换到 postgres 用户
sudo -i -u postgres
2. 进入 PostgreSQL 命令行
psql
3. 设置 postgres 用户密码
ALTER USER postgres PASSWORD 'your_password';
替换
your_password为强密码。
4. 退出 psql
q
5. 退出 postgres 用户
exit
✅ 四、允许远程连接(可选)
1. 修改 postgresql.conf
路径通常为:
- Ubuntu:
/etc/postgresql/版本/main/postgresql.conf - CentOS:
/var/lib/pgsql/15/data/postgresql.conf
编辑文件:
sudo vim /var/lib/pgsql/15/data/postgresql.conf
找到并修改:
listen_addresses = 'localhost' # 改为:
listen_addresses = '*' # 或 '0.0.0.0' 允许所有 IP
建议生产环境指定具体 IP,如
'192.168.1.100,127.0.0.1'
2. 修改 pg_hba.conf(访问控制)
路径:
- Ubuntu:
/etc/postgresql/版本/main/pg_hba.conf - CentOS:
/var/lib/pgsql/15/data/pg_hba.conf
添加一行允许远程连接(示例):
# TYPE DATABASE USER ADDRESS METHOD
host all all 0.0.0.0/0 md5
生产环境建议限制 IP 范围,如
112.95.100.0/24
3. 重启 PostgreSQL
- Ubuntu:
sudo systemctl restart postgresql - CentOS:
sudo systemctl restart postgresql-15
✅ 五、配置腾讯云安全组(关键!)
- 登录 腾讯云控制台
- 找到你的云服务器 → 安全组 → 编辑入站规则
- 添加规则:
- 协议类型:TCP
- 端口:
5432 - 源 IP:
0.0.0.0/0(测试用)或指定 IP - 策略:允许
⚠️ 生产环境不要开放 0.0.0.0/0,建议限制访问 IP。
✅ 六、测试连接
1. 本地测试
psql -U postgres -h localhost -p 5432
2. 外部工具连接(如 DBeaver、Navicat)
- 主机:你的腾讯云公网 IP
- 端口:5432
- 用户名:
postgres - 密码:你设置的密码
✅ 七、常见问题排查
| 问题 | 解决方法 |
|---|---|
| 连接被拒 | 检查 listen_addresses 和 pg_hba.conf |
| 无法远程连接 | 检查腾讯云安全组是否开放 5432 端口 |
| 权限错误 | 检查 pg_hba.conf 的 METHOD 是否为 md5 |
| 服务未启动 | systemctl status postgresql 查看日志 |
✅ 附加建议
-
创建专用数据库和用户:
CREATE DATABASE myapp; CREATE USER myuser WITH ENCRYPTED PASSWORD 'mypass'; GRANT ALL PRIVILEGES ON DATABASE myapp TO myuser; -
定期备份:
pg_dump -U postgres myapp > backup.sql
如果你提供具体的系统版本(如 Ubuntu 20.04),我可以给出更精确的命令。欢迎继续提问!
秒懂云