我想复制一个生产PostgreSQL数据库到一个开发服务器。最快最简单的方法是什么?


当前回答

如果你想在版本之间迁移(例如你更新了postgres,在localhost:5432上运行9.1,在localhost:5434上运行9.3),你可以运行:

pg_dumpall -p 5432 -U myuser91 | psql -U myuser94 -d postgres -p 5434

查看迁移文档。

其他回答

如果您更喜欢使用GUI,您可以使用pgAdmin软件。

连接到源服务器和目标服务器 右键单击源db > backup 右键单击目标服务器>创建>数据库。使用与源db相同的属性(通过右键单击> properties可以看到源db的属性) 右键单击创建的db >恢复。

Pg_basebackup现在似乎是更好的方式,特别是对于大型数据库。

可以从具有相同或较旧主版本的服务器复制数据库。或者更准确地说:

Pg_basebackup适用于相同或更老版本(低至9.1)的服务器。但WAL流模式(-X stream)仅适用于9.3及以后的服务器版本,当前版本的tar格式模式(——format=tar)仅适用于9.5及以后的服务器版本。

对于源服务器,您需要:

listen_addresses = '*' to be able to connect from the target server. Make sure port 5432 is open for that matter. At least 1 available replication connection: max_wal_senders = 1 (-X fetch), 2 for -X stream (the default in case of PostgreSQL 12), or more. wal_level = replica or higher to be able to set max_wal_senders > 0. host replication postgres DST_IP/32 trust in pg_hba.conf. This grants access to the pg cluster to anyone from the DST_IP machine. You might want to resort to a more secure option.

更改1、2、3需要重新启动服务器,更改4需要重新加载。

在目标服务器上:

# systemctl stop postgresql@VERSION-NAME
postgres$ pg_basebackup -h SRC_IP -U postgres -D VERSION/NAME --progress
# systemctl start postgresql@VERSION-NAME

以数据库名称运行此命令,如果要备份,则转储数据库。

 pg_dump -U {user-name} {source_db} -f {dumpfilename.sql}

 eg. pg_dump -U postgres mydbname -f mydbnamedump.sql

现在将这个转储文件scp到您想要复制DB的远程机器。

eg. scp mydbnamedump.sql user01@remotemachineip:~/some/folder/

在远程机器上,在~/some/文件夹中运行以下命令来恢复DB。

 psql -U {user-name} -d {desintation_db}-f {dumpfilename.sql}

 eg. psql -U postgres -d mynewdb -f mydbnamedump.sql

转储数据库:pg_dump database_name_name > backup.sql


导入数据库:psql db_name < backup.sql

我努力了很多,最终让我在Rails 4中工作的方法是:

在旧服务器上

sudo su - postgres
pg_dump -c --inserts old_db_name > dump.sql

我必须使用postgres linux用户来创建转储。我还必须使用-c来强制在新服务器上创建数据库。——inserts告诉它使用INSERT()语法,否则对我来说是无效的:(

然后,在新服务器上,simpy:

sudo su - postgres
psql new_database_name < dump.sql

传输转储。我简单地使用“cat”来打印内容,而不是“nano”来重新创建它复制粘贴内容。

此外,我在两个数据库上使用的角色是不同的,所以我必须在转储中找到-替换所有的所有者名称。