Square CloudSquare Cloud

How to migrate a database to another server (dump and restore)

Stop writes, take a dump on the source with the engine's own tool, restore it on the new server and check the data before switching the URL. For PostgreSQL use pg_dump and pg_restore; for MySQL, mysqldump; for MongoDB, mongodump and mongorestore.

Updated 8 min read

Learning objectives

After reading this article you will be able to:

  • Plan a rehearsal and the write freeze before the switch
  • Migrate PostgreSQL, MySQL, MongoDB and Redis with each engine's tools
  • Check the data on the destination and handle version differences
On this page

Migrating a database to another server means copying the data from one place to another and pointing the application at the new place, without losing a single write along the way. The most portable route is a logical dump: the engine's own tool exports the contents into a file, and that file loads into another server, at another provider, often on a newer version.

This guide covers moving servers. If you are looking for how to apply schema changes on every deploy, that is a different topic: see database migrations on deploy. The dump and restore commands also appear in how to back up a database; here the focus is the switch itself.

What should you prepare before migrating?#

  • The versions on both sides. Write down the engine version on the source and on the destination (SELECT version(); on PostgreSQL and MySQL, db.version() in mongosh, INFO server on Redis). Each engine's compatibility rules are in the sections below.
  • The client tools. Use pg_dump, mysqldump and mongodump in a version compatible with both servers; for PostgreSQL, the newer of the two.
  • A machine with a good network path to both sides. The file goes through it, so disk and bandwidth matter.
  • Access to the destination, with host, port, user, password and, if it requires TLS, the CA and the client certificate. A certificate error during the restore has the same diagnosis as the self-signed certificate error when connecting to a database.
  • What isn't table data. Extensions, users, scheduled jobs and the total size. List what the source uses and check that the destination offers it.

Avoid passwords on the command line, where they show up in shell history and the process list. On a shared machine, use the tools' credential files, such as ~/.pgpass and ~/.my.cnf.

How do you plan the write freeze?#

A dump captures the database at one instant. Whatever the application writes after it never reaches the destination. That is why the switch has a window where nobody writes:

  1. Rehearse. With the application live, take a dump, restore it into a test database on the destination and time both steps. Fix the errors now, not on the night of the switch.
  2. Announce and stop writes. Shut the application down, turn on a maintenance mode or stop the workers that write. Read-only counts as stopped.
  3. Take the final dump on the source.
  4. Restore it on the destination and run the checks from the last section.
  5. Switch the URL in the application's environment variable and restart.
  6. Keep the source untouched for a few days. If something goes wrong, you switch back to the old URL.

The window lasts as long as the dump plus the restore, and the rehearsal tells you how long that is. If your business can't afford it, the alternative is replication (logical on PostgreSQL, native on MySQL), which needs replication permissions on both servers.

How do you migrate a PostgreSQL database?#

Use the custom format (-Fc), which is compressed and can be restored in parallel. The URLs live in variables; the destination's carries libpq's TLS parameters:

bash
export SOURCE_URL="postgresql://app:password@source.example.com:5432/app"
export DEST_URL="postgresql://app:password@dest.example.com:5432/app?sslmode=verify-full&sslrootcert=ca.pem&sslcert=client-cert.pem&sslkey=client-key.pem"

pg_dump -d "$SOURCE_URL" -Fc --no-owner --no-acl -f app.dump
pg_restore -d "$DEST_URL" --no-owner --no-acl -j 4 app.dump
psql "$DEST_URL" -c "ANALYZE;"
  • --no-owner and --no-acl leave out the source's object owners and GRANTs. pg_dump doesn't carry roles, and the destination user rarely has the same name.
  • -j 4 loads data and builds indexes in four sessions at once.
  • pg_restore keeps going after an error and prints the count at the end. Read each one before moving on.
  • ANALYZE refreshes the planner statistics, so the first queries aren't slow.

Versions. pg_dump output loads into newer servers, but pg_dump refuses to dump a server newer than itself, and loading into an older server isn't guaranteed. The PostgreSQL documentation recommends the newer version's pg_dump when you change versions.

Extensions. The dump includes a CREATE EXTENSION for each extension on the source. If the destination lacks one of them, the objects that depend on it fail during the restore.

How do you migrate a MySQL database?#

bash
mysqldump -h source.example.com -u app -p \
  --single-transaction --routines --triggers --events \
  --no-tablespaces --result-file=app.sql app

mysql -h dest.example.com -P 3306 -u app -p \
  --ssl-mode=VERIFY_IDENTITY --ssl-ca=ca.pem app < app.sql
  • --single-transaction reads a consistent view of InnoDB tables without locking writes.
  • --routines and --events include stored procedures and scheduled events, which are left out by default.
  • --no-tablespaces removes the need for the PROCESS privilege, which mysqldump requires without this option and which regular users often lack.
  • Without --databases, the file has no CREATE DATABASE or USE, and you pick the destination database at restore time.
  • If the source is MySQL with GTIDs, add --set-gtid-purged=OFF so the dump doesn't try to set gtid_purged on the destination server.

VERIFY_IDENTITY checks the CA and the host name; VERIFY_CA checks only the CA. PowerShell has no < operator: run mysql ... app -e "source app.sql" instead.

Versions. In the MySQL documentation's upgrade path table, a logical dump and load works within a series and into the next LTS series, but an LTS series can't be skipped: if the destination is further ahead, move up one series at a time. The documentation recommends running MySQL Shell's upgrade checker (util.checkForServerUpgrade()) first.

Moving between MariaDB and MySQL is more than a version change: the two differ in types, collations and syntax. Rehearse the restore and see MariaDB vs MySQL.

How do you migrate a MongoDB database?#

bash
mongodump --uri="$SOURCE_URI" --db=app --gzip --archive=app.archive.gz

mongorestore --uri="$DEST_URI" \
  --ssl --sslCAFile=ca.pem --sslPEMKeyFile=client.pem \
  --gzip --archive=app.archive.gz --nsInclude="app.*"

--sslPEMKeyFile takes a .pem holding both the client certificate and key. The --tlsCAFile and --tlsCertificateKeyFile options you may know from mongosh don't exist in mongodump or mongorestore; those names only work inside the URI (?tls=true&tlsCAFile=ca.pem&tlsCertificateKeyFile=client.pem). If the URI already sets TLS, don't repeat it in the options with different values: the tool rejects the conflict.

To rename the database on the way, use --nsFrom="app.*" --nsTo="newname.*". Indexes travel in the dump and are rebuilt on restore. Don't restore the source's admin, config and local databases: a dump of just your database already leaves them out, and the destination keeps the user it already has.

Versions. The MongoDB documentation only guarantees restoring a dump into a server with the same major version or feature compatibility version (FCV) as the source. If the lines differ, the covered path is matching the versions before the final dump, by upgrading the source to the destination's line; otherwise, only the rehearsal and the count checks tell you whether it worked.

How do you migrate Redis?#

If you control both servers, the fastest route is copying the source's dump.rdb into the destination's data directory before starting it. On a hosted destination with no disk access, copy key by key with DUMP and RESTORE, which keep the type and the contents:

python
# copy_redis.py  (pip install redis)
import os

import redis

source = redis.Redis.from_url(os.environ["REDIS_SOURCE_URL"])
dest = redis.Redis.from_url(os.environ["REDIS_DEST_URL"], ssl_ca_certs="ca.pem")

copied = 0
for key in source.scan_iter(count=1000):
    value = source.dump(key)
    ttl = source.pttl(key)  # -1: no expiry; -2: the key is gone
    if value is None or ttl == -2:
        continue
    dest.restore(key, max(ttl, 0), value, replace=True)
    copied += 1

print(f"{copied} keys copied, {dest.dbsize()} on the destination")

DUMP doesn't carry the expiry, so the script reads PTTL and passes it to RESTORE (0 means no expiry). The serialized value carries the RDB format version, and a server that doesn't recognize that version rejects the RESTORE: test with a few keys first. If the TLS connection to the destination fails, see Redis connection errors. If the source uses several logical databases (SELECT 1, SELECT 2), run the script once per database, with key prefixes, when the destination has only one.

How do you check that the migration worked?#

Compare counts on both sides before switching the URL. On PostgreSQL, this query returns the exact count of every table; run it on both servers and compare the output:

sql
SELECT table_schema, table_name,
  (xpath('/row/c/text()', query_to_xml(
    format('SELECT count(*) AS c FROM %I.%I', table_schema, table_name),
    false, true, '')))[1]::text::bigint AS row_count
FROM information_schema.tables
WHERE table_type = 'BASE TABLE'
  AND table_schema NOT IN ('pg_catalog', 'information_schema')
ORDER BY 1, 2;

On MySQL, use SELECT COUNT(*) on the main tables: the TABLE_ROWS column in information_schema is only an estimate for InnoDB. On MongoDB, in mongosh:

javascript
db.getCollectionNames().forEach((c) => print(c, db.getCollection(c).countDocuments({})));

On Redis, compare DBSIZE on both sides and check the TTL of a few expiring keys.

After the counts, start the application against the destination and test the flows that read and write. On PostgreSQL, the dump already carries each sequence's current value, so new IDs pick up where they left off. If the source had a backup routine, set it up again for the new server. And if the application's files are also changing providers, the copy follows the same rehearse-and-check logic: see how to migrate files between S3 providers.

How to do this on Square Cloud#

On Square Cloud, the destination is a database you create in the dashboard (MongoDB, PostgreSQL, MySQL or Redis, from the Standard plan), always on the engine's recent version: you don't pick the version, so check the one on the database you created and follow each section's version rules in the rehearsal. PostgreSQL ships with the pgvector and pg_cron extensions. The database accepts outside connections with host, port, password and certificate, so pg_restore, mysql, mongorestore or the Redis script run from your machine or from CI.

  1. Create the database and copy the connection URL, shown once at creation (resetting the password shows it again).
  2. Download the certificate. TLS is mandatory: pass the CA to the tools (sslrootcert, --ssl-ca, --sslCAFile) and, for PostgreSQL and MongoDB, the client certificate too (sslcert and sslkey, or --sslPEMKeyFile). Redis uses rediss:// and has a single logical database.
  3. Before importing, take a manual snapshot of the destination database. If the import goes wrong, you restore that snapshot to the same database, to another one of the same engine or to a new database.
  4. After the checks, copy the URL into the application's environment variable and restart: the change applies on the next restart.

For a quick look at the imported tables, the dashboard has a data explorer; for the actual checks, use the queries above. From then on, the database gets a daily automatic snapshot, kept for 7 days. See engines and plans on database hosting.

Database hosting

MongoDB, PostgreSQL, MySQL and Redis next to your app

Database hosting

FAQs

Can I migrate a database without taking the app offline?

Not with dump and restore: anything written after the dump is left behind, so you need a window with no writes. Removing the window takes replication between source and destination, which needs replication permissions on both servers.

Can I restore a dump from an older version on a newer server?

On PostgreSQL, yes: pg_dump output loads into newer versions, but isn't guaranteed on an older one. On MySQL, the documentation supports a logical dump up to the next LTS series, without skipping a series. On MongoDB, it only guarantees restores into the same major version or feature compatibility version as the source.

Does pg_dump copy users and permissions?

No. It copies a single database; roles are cluster-wide and come out with pg_dumpall --globals-only. On a hosted destination, use --no-owner and --no-acl so the destination user owns everything.

How long does a migration take?

It depends on data size, indexes and the network between the machines. Measure it in the rehearsal: dump time plus restore time is the window you will need.

Next articlePrisma, Drizzle, TypeORM or Sequelize: which Node.js ORM to usePrisma and Drizzle are the natural picks for new TypeScript projects; TypeORM and Sequelize are still in use. Compare criteria, code and when raw SQL is enough.

More in Databases

See all 32 articles