Docker容器内脚本备份宿主机PostgreSQL数据库问题及解决
Docker容器内执行PostgreSQL备份脚本的问题与解决
背景
原本在Ubuntu服务器上运行正常的PostgreSQL备份脚本命令如下:
pg_dump -U postgres -w -h 127.0.0.1 -F t $NOME_DA_BD > $BACKUP_PATH$BACKUP_NAME
尝试将该脚本放入Docker容器内执行,对应的Dockerfile内容:
FROM ubuntu:20.04 FROM postgres:17.0 COPY backup.sh /usr/local/bin/ WORKDIR /usr/local/bin/ RUN chmod +x backup.sh # debconf: 延迟包配置,因为未安装apt-utils RUN apt-get update && apt-get install -y bash && apt-get -y install cron # RUN sudo apt install postgresql CMD ["/bin/bash"] # RUN /bin/bash -c 'ls /usr/local/bin/'
构建并运行容器的命令:
$ sudo docker build --no-cache -t hcorte/bakcup_container . $ sudo docker run -v /mnt/backups/:/mnt/backups/ --add-host host.docker.internal:host-gateway -it hcorte/bakcup_container bash root@79fc9d37136b:/usr/local/bin# sh backup.sh 10
遇到的问题
已将脚本中的数据库连接地址从127.0.0.1改为host.docker.internal,目的是备份宿主机上的数据库而非容器内的,但执行时先出现连接拒绝错误:
pg_dump: 错误:连接到"host.docker.internal"(172.17.0.1)的服务器,端口5432失败:连接被拒绝 服务器是否在该主机上运行并接受TCP/IP连接?
调整后又出现新错误:
pg_dump: 错误:连接到"host.docker.internal"(172.17.0.1)的服务器,端口5432失败:FATAL: 主机"172.17.0.2"、用户"postgres"、数据库"dvdrental"的SSL加密连接在pg_hba.conf中无对应条目 连接到"host.docker.internal"(172.17.0.1)的服务器,端口5432失败:FATAL: 主机"172.17.0.2"、用户"postgres"、数据库"dvdrental"的无加密连接在pg_hba.conf中无对应条目
解决方法
修改宿主机上的/etc/postgresql/17/main/pg_hba.conf文件,添加一条测试用规则(后续可调整为更安全的配置):
hostnossl all all 0.0.0.0/0 trust
核心是需要修改PostgreSQL的配置,允许Docker容器连接到宿主机数据库并执行备份操作。
内容的提问来源于stack exchange,提问作者H.C
相关产品推荐
相关产品推荐

