我正在将应用程序迁移到 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/