在腾讯云服务器上安装 PostgreSQL 是一个常见的需求,适用于搭建 Web 应用、数据库服务等。以下是详细的安装步骤(以 CentOS 7/8 和 Ubuntu 20.04/22.04 为例):
🛠️ 前提准备
- 腾讯云已创建并登录 Linux 云服务器(CVM)
- 确保服务器可以访问X_X(用于下载软件包)
- 使用 root 或具有 sudo 权限的用户操作
✅ 方法一:Ubuntu 系统安装 PostgreSQL
1. 更新系统包
sudo apt update && sudo apt upgrade -y
2. 安装 PostgreSQL
sudo apt install postgresql postgresql-contrib -y
3. 启动并设置开机自启
sudo systemctl start postgresql
sudo systemctl enable postgresql
4. 检查状态
sudo systemctl status postgresql
5. 切换到 postgres 用户并进入 psql
sudo -u postgres psql
6. 修改默认密码(可选)
ALTER USER postgres PASSWORD 'your_password';
替换
your_password
为你的强密码。
7. 允许远程连接(如需)
修改配置文件:
sudo nano /etc/postgresql/*/main/postgresql.conf
找到并修改:
listen_addresses = 'localhost' # 改为
listen_addresses = '*'
配置客户端认证:
sudo nano /etc/postgresql/*/main/pg_hba.conf
添加一行允许远程 IP 连接(例如允许所有 IPv4):
host all all 0.0.0.0/0 md5
重启服务
sudo systemctl restart postgresql
开放防火墙端口(默认 5432)
sudo ufw allow 5432/tcp
⚠️ 注意:开放公网访问时请确保安全组也放行了 5432 端口,并建议限制 IP 白名单。
✅ 方法二:CentOS / Rocky Linux / RHEL 安装 PostgreSQL
1. 添加官方 PostgreSQL Yum 源
前往 https://www.postgresql.org/download/linux/redhat/ 选择版本。
例如安装 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 对应 CentOS 8)
2. 安装 PostgreSQL 服务
sudo yum install -y postgresql15-server postgresql15
3. 初始化数据库
sudo /usr/pgsql-15/bin/postgresql-15-setup initdb
4. 启动并启用开机启动
sudo systemctl start postgresql-15
sudo systemctl enable postgresql-15
5. 检查状态
sudo systemctl status postgresql-15
6. 切换用户并设置密码
sudo -u postgres psql
在 psql 中执行:
ALTER USER postgres PASSWORD 'your_secure_password';
7. 配置远程访问(同上)
编辑配置文件:
sudo nano /var/lib/pgsql/15/data/postgresql.conf
修改:
listen_addresses = '*'
编辑:
sudo nano /var/lib/pgsql/15/data/pg_hba.conf
添加:
host all all 0.0.0.0/0 md5
重启服务:
sudo systemctl restart postgresql-15
开放防火墙:
sudo firewall-cmd --permanent --add-port=5432/tcp
sudo firewall-cmd --reload
🔐 安全建议
-
不要直接使用公网暴露 5432 端口
- 使用腾讯云安全组限制访问 IP
- 推荐通过 SSH 隧道或内网连接
-
创建专用数据库用户,避免使用
postgres
账户直连应用 -
定期备份数据
-
修改默认端口(可选)提升安全性
🌐 腾讯云安全组配置
登录 腾讯云控制台
- 找到你的 CVM 实例
- 查看关联的安全组
- 编辑入站规则,添加:
- 协议类型:TCP
- 端口:5432
- 源 IP:建议填写你的固定 IP(如
123.123.123.123/32
),或内网互通段 - 策略:允许
❗ 生产环境不建议填
0.0.0.0/0
✅ 测试连接
你可以使用本地工具(如 DBeaver、Navicat)或命令行测试连接:
psql -h your_server_ip -U postgres -p 5432 -W
📚 参考文档
- PostgreSQL 官网:https://www.postgresql.org
- 腾讯云 CVM 文档:https://cloud.tencent.com/document/product/213
如有具体系统版本或特殊需求(如 Docker 安装、高可用部署),欢迎继续提问!