我想复制一个生产PostgreSQL数据库到一个开发服务器。最快最简单的方法是什么?
当前回答
接受的答案是正确的,但如果你想避免交互式输入密码,你可以使用这个:
PGPASSWORD={{export_db_password}} pg_dump --create -h {{export_db_host}} -U {{export_db_user}} {{export_db_name}} | PGPASSWORD={{import_db_password}} psql -h {{import_db_host}} -U {{import_db_user}} {{import_db_name}}
其他回答
先使用pg_dump,然后再使用psql或pg_restore——这取决于您是选择- fp选项还是- fc选项来使用pg_dump。
用法示例:
ssh production
pg_dump -C -Fp -f dump.sql -U postgres some_database_name
scp dump.sql development:
rm dump.sql
ssh development
psql -U postgres -f dump.sql
您不需要创建中间文件。你可以这样做
pg_dump -C -h localhost -U localuser dbname | psql -h remotehost -U remoteuser dbname
or
pg_dump -C -h remotehost -U remoteuser dbname | psql -h localhost -U localuser dbname
使用PSQL或pg_dump连接到远程主机。
对于大数据库或慢速连接,转储文件和传输压缩文件可能更快。
正如Kornel所说,没有必要转储到中间文件,如果你想压缩工作,你可以使用压缩隧道
pg_dump -C dbname | bzip2 | ssh remoteuser@remotehost "bunzip2 | psql dbname"
or
pg_dump -C dbname | ssh -C remoteuser@remotehost "psql dbname"
但是这个解决方案还需要在两端都获得一个会话。
注:pg_dump用于备份,psql用于恢复。因此,这个答案中的第一个命令是从本地复制到远程,第二个命令是从远程复制到本地。更多-> https://www.postgresql.org/docs/9.6/app-pgdump.html
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
让我分享一个Linux shell脚本,将你的表数据从一个服务器复制到另一个PostgreSQL服务器。
参考本博客:
用于PostgreSQL服务器间数据迁移的Linux Bash Shell脚本:
#!/bin/bash
psql \
-X \
-U user_name \
-h host_name1 \
-d database_name \
-c "\\copy tbl_Students to stdout" \
| \
psql \
-X \
-U user_name \
-h host_name2 \
-d database_name \
-c "\\copy tbl_Students from stdin"
我只是在迁移数据;请在目标/第二个数据库服务器上创建一个空表。
这是一个实用程序脚本。此外,您还可以修改脚本以使其具有通用用途,例如为host_name、database_name、table_name等添加参数
pg_dump the_db_name > the_backup.sql
然后将备份复制到您的开发服务器,使用以下方法进行恢复:
psql the_new_dev_db < the_backup.sql
推荐文章
- 将表从一个数据库复制到另一个数据库的最简单方法?
- 截断Postgres数据库中的所有表
- 什么是分片,为什么它很重要?
- 如何连接列在Postgres选择?
- 数据库触发器是必要的吗?
- 为什么我应该使用基于文档的数据库而不是关系数据库?
- 哪个更快/最好?SELECT *或SELECT columnn1, colum2, column3等
- 将varchar字段的类型更改为整数:"不能自动转换为整数类型"
- 将值从同一表中的一列复制到另一列
- PostgreSQL可以索引数组列吗?
- 什么是数据库池?
- 关于数据库,每个开发人员应该知道些什么?
- PostgreSQL:角色不允许登录
- "where 1=1"语句
- 如何查找Postgres / PostgreSQL表及其索引的磁盘大小