gpt4 book ai didi

postgresql - 将 PostgreSQL 数据库备份加载到 Docker/初始 Docker 数据中

转载 作者:行者123 更新时间:2023-11-29 12:05:20 27 4
gpt4 key购买 nike

我正在将应用程序迁移到 Docker。我遇到的问题之一是将初始数据加载到在 Docker 中运行的 PostgreSQL 的正确方法是什么?我恢复数据库备份文件的典型方法不起作用。我尝试了以下方法:

gunzip -c mydbbackup.sql.gz | psql -h <docker_host> -p <docker_port> -U <dbuser> -d <db> -W

那行不通,因为 PostgreSQL 提示输入密码,而我无法输入密码,因为它正在从 STDOUT 读取数据。我不能使用 $PGPASSWORD 环境变量,因为我在主机中设置的任何环境变量都没有在我的容器中设置。

除了使用 -f 标志,我还尝试了上面类似的命令,并指定了 sql 备份文件的路径。这不起作用,因为我的文件不在我的容器中。我可以使用我的 Dockerfile 中的 ADD 语句将文件复制到我的容器,但这似乎不对。

所以,我问社区。将 PostgreSQL 数据库备份加载到 Docker 容器的首选方法是什么?

最佳答案

I cannot use the $PGPASSWORD environment variable, because the any environment variable I set in my host is not set in my container.

我不使用 docker,但您的容器在显示的命令中看起来像一个远程主机,psql 在本地运行。所以 PGPASSWORD 永远不必在远程主机上设置,只需在本地设置即可。

如果问题归结为向此命令添加密码:

gunzip -c mydbbackup.sql.gz |
psql -h <docker_host> -p <docker_port> -U <dbuser> -d <db> -W

您可以使用多种方法提交它(在所有情况下,不要使用 psql 的 -W 选项)

  • 在调用中硬编码:

     gunzip -c mydbbackup.sql.gz |
    PGPASSWORD=something psql -h <docker_host> -p <docker_port> -U <dbuser> -d <db>
  • 在键盘上打字

     echo -n "Enter password:"
    read -s PGPASSWORD
    export PGPASSWORD
    gunzip -c mydbbackup.sql.gz |
    psql -h <docker_host> -p <docker_port> -U <dbuser> -d <db>

注意 psql 的 -W--password 选项。

此选项的要点是要求首先输入密码,即使上下文不需要。

它经常被误解为等同于 mysql 的 -p 选项。这是一个错误:虽然 -p 在受密码保护的连接上是必需的,但从不需要 -W 并且实际上在编写脚本时会妨碍。

       -W, --password           Force psql to prompt for a password before connecting to a           database.           This option is never essential, since psql will automatically           prompt for a password if the server demands password           authentication. However, psql will waste a connection attempt           finding out that the server wants a password. In some cases it is           worth typing -W to avoid the extra connection attempt.

关于postgresql - 将 PostgreSQL 数据库备份加载到 Docker/初始 Docker 数据中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24995944/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com