[debian postgres]
<h2 id="一套标准完整且可直接复制使用的安装配置命令">一套标准、完整且可直接复制使用的安装配置命令。</h2><h3 id="一完整安装配置命令">一、完整安装配置命令</h3>
<p>以下命令适用于 Debian 10 (Buster)、11 (Bullseye)、12 (Bookworm) 等主流版本,全程使用 root 权限执行(如果非 root 用户,需在每个命令前加 <code>sudo</code>)。</p>
<pre><code class="language-bash"># 1. 更新系统软件包索引
apt update && apt upgrade -y
# 2. 安装PostgreSQL(默认安装最新稳定版,Debian官方源已内置)
apt install -y postgresql postgresql-contrib
# 3. 验证服务状态(确认PostgreSQL是否正常启动)
systemctl status postgresql --no-pager
# 4. 切换到postgres系统用户(PostgreSQL默认的管理员用户)
su - postgres
# 5. 登录PostgreSQL命令行
psql
# 6. 在PostgreSQL命令行中执行以下配置(创建自定义用户、数据库,设置密码)
# 替换 your_user 为你想要的用户名,your_password 为密码,your_db 为数据库名
CREATE USER your_user WITH PASSWORD 'your_password';
CREATE DATABASE your_db OWNER your_user;
GRANT ALL PRIVILEGES ON DATABASE your_db TO your_user;
# 7. 退出PostgreSQL命令行
\q
# 8. 退出postgres用户,回到root
exit
# 9. (可选)修改PostgreSQL监听地址(允许远程连接)
# 编辑配置文件
nano /etc/postgresql/$(ls /etc/postgresql)/main/postgresql.conf
# 在文件中找到 listen_addresses,修改为 *(监听所有地址)
# listen_addresses = '*'
# 10. (可选)配置远程访问权限
# 编辑pg_hba.conf文件
nano /etc/postgresql/$(ls /etc/postgresql)/main/pg_hba.conf
# 在文件末尾添加(允许任意IP访问,根据需求调整)
# host all all 0.0.0.0/0 scram-sha-256
# 11. (可选)重启PostgreSQL使配置生效
systemctl restart postgresql
# 12. (可选)设置PostgreSQL开机自启(默认已开启,可验证)
systemctl enable postgresql
</code></pre>
<h3 id="二关键命令解释">二、关键命令解释</h3>
<ol>
<li><strong>软件安装</strong>:
<ul>
<li><code>postgresql</code>:核心数据库服务包;</li>
<li><code>postgresql-contrib</code>:包含额外的实用工具和扩展,建议一起安装。</li>
</ul>
</li>
<li><strong>用户切换</strong>:
<ul>
<li>Debian 安装 PostgreSQL 后会自动创建 <code>postgres</code> 系统用户,这是数据库的默认管理员,必须切换到该用户才能直接登录数据库。</li>
</ul>
</li>
<li><strong>远程连接配置</strong>:
<ul>
<li><code>listen_addresses = '*'</code>:让 PostgreSQL 监听所有网卡地址(默认只监听本地 127.0.0.1);</li>
<li><code>pg_hba.conf</code>:PostgreSQL 的访问控制文件,<code>0.0.0.0/0</code> 表示允许所有IP访问(生产环境建议替换为具体IP段,如 <code>192.168.1.0/24</code>),<code>scram-sha-256</code> 是密码认证方式(Debian 11+ 默认使用)。</li>
</ul>
</li>
</ol>
<h3 id="三验证安装">三、验证安装</h3>
<p>执行以下命令,若能正常登录数据库,说明安装成功:</p>
<pre><code class="language-bash">su - postgres
psql -c "SELECT version();"
</code></pre>
<p>输出类似如下内容即为正常:</p>
<pre><code> version
------------------------------------------------------------------------------------------------------------------
PostgreSQL 15.5 (Debian 15.5-0+deb12u1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit
(1 row)
</code></pre>
<h3 id="总结">总结</h3>
<ol>
<li>Debian 安装 PostgreSQL 核心命令是 <code>apt install postgresql postgresql-contrib</code>,安装前需先更新软件源;</li>
<li>默认需切换到 <code>postgres</code> 用户操作数据库,创建自定义用户和数据库是使用前的必要步骤;</li>
<li>若需远程访问,需修改 <code>postgresql.conf</code> 和 <code>pg_hba.conf</code> 两个配置文件并重启服务。</li>
</ol><br><br>
来源:https://www.cnblogs.com/shiyuzhahan/p/19482847
頁:
[1]