无法通过WireGuard连接Docker部署的PostgreSQL数据库求助
问题描述
成功搭建了服务器-客户端(2节点)的WireGuard VPN网络,此前一切正常,但无法通过VPN连接服务器上Docker部署的PostgreSQL数据库。
环境配置
Docker Compose配置
version: "3" services: db: container_name: postgres image: postgres:15-alpine command: ["postgres"] ports: - 127.0.0.1:5432:5432 - 192.168.22.1:5432:5432 env_file: ./.env.db networks: - backend restart: always
服务器主机通过127.0.0.1:5432和192.168.22.1:5432均可访问数据库,端口映射配置正常。
WireGuard配置
- 服务器端
wg0.conf
[Interface] Address = 192.168.22.1 PrivateKey = [redacted] ListenPort = 51820 [Peer] PublicKey = [redacted] AllowedIPs = 192.168.22.2/32
- 客户端
wg0.conf
[Interface] Address = 192.168.22.2 PrivateKey = [redacted] ListenPort = 21841 [Peer] PublicKey = [redacted] Endpoint = [ip redacted]:51820 AllowedIPs = 192.168.22.0/24 PersistentKeepalive = 25
测试结果
- WireGuard连通性正常:服务器执行
nc -l 192.168.22.1 4444,客户端执行nc 192.168.22.1 4444,双向通信正常。 - 客户端连接PostgreSQL失败:
pg_dump -h 192.168.22.1 -p 5432 -U postgres postgres pg_dump: error: connection to database "postgres" failed: could not connect to server: Connection timed out Is the server running on host "192.168.22.1" and accepting TCP/IP connections on port 5432?
- 服务器
lsof显示端口监听正常:
sudo lsof -nP -iTCP -sTCP:LISTEN # 输出包含: docker-pr 4225 root 4u IPv4 44625 0t0 TCP 192.168.22.1:5432 (LISTEN) docker-pr 4251 root 4u IPv4 60392 0t0 TCP 127.0.0.1:5432 (LISTEN)
补充信息
iptables --list显示FORWARD链默认DROP,DOCKER-ISOLATION-STAGE-2会DROP所有跨网桥流量。ip route显示WireGuard路由正常,但Docker网桥网段与WireGuard网段分离。
解决方案
1. 放开PostgreSQL容器内部的访问限制
容器内的PostgreSQL默认可能仅允许本地或Docker网段访问,需要修改pg_hba.conf添加WireGuard网段的访问权限:
- 进入PostgreSQL容器:
docker exec -it postgres bash
- 追加访问规则到配置文件:
echo "host all all 192.168.22.0/24 scram-sha-256" >> /var/lib/postgresql/data/pg_hba.conf
- 重启容器生效:
docker restart postgres
2. 调整iptables规则允许WireGuard网段转发到Docker
当前Docker的隔离规则会阻止非Docker网段的流量转发到容器,需要添加规则允许WireGuard网段的流量通过:
- 临时添加规则(立即生效,重启后失效):
sudo iptables -A DOCKER-USER -s 192.168.22.0/24 -j ACCEPT
- 永久保存规则(以Ubuntu为例):
sudo iptables-save > /etc/iptables/rules.v4
3. 验证配置
客户端再次尝试连接:
pg_dump -h 192.168.22.1 -p 5432 -U postgres postgres
如果仍失败,可进入容器检查postgresql.conf是否设置listen_addresses = '*'(容器默认通常已配置)。
内容的提问来源于stack exchange,提问作者Stefan Wobbe
相关产品推荐
相关产品推荐

