MySQL Database Migration Between Two Servers Safely
In this article
This guide walks you through migrating a MySQL database from one server to another with minimal downtime and zero data loss. You'll learn how to dump the data on the source, transfer it securely, and import it on the target, plus how to verify everything matches before switching over.
What You'll Need
- SSH access to both the source and target servers.
- MySQL client tools (
mysqldump,mysql) installed on both servers. - Sufficient disk space on the target server for the imported data (at least the size of the source database).
- Credentials for a MySQL user with
SELECT,LOCK TABLES, andRELOADprivileges on the source, andCREATE,INSERT,ALTER, andDROPprivileges on the target. - If you're moving to a different MySQL version, check compatibility (e.g., 5.7 to 8.0) before starting.
Step-by-Step
- Plan the migration window. Choose a time when write activity is low. For a fully consistent snapshot, you'll need to briefly lock tables or stop writes during the dump.
- Create a backup on the source server. Run the following command, replacing
dbnamewith your database name andbackup.sqlwith your desired filename:
Themysqldump -u root -p --single-transaction --routines --triggers --events dbname > backup.sql--single-transactionflag uses InnoDB's transaction isolation to get a consistent snapshot without locking all tables. If you use MyISAM tables, omit this flag and use--lock-tablesinstead (this will briefly lock writes). - Verify the dump file. Check that the file is not empty and look at the first few lines:
You should see SQL statements and no error messages.ls -lh backup.sql head -n 20 backup.sql - Transfer the dump to the target server. Use
scporrsyncover SSH. For example:
If the file is large, consider compressing it first:scp backup.sql user@target-server:/tmp/gzip backup.sqlthen transfer the.gzfile and decompress on the target. - Create the database on the target server (if needed). If the database doesn't already exist, log into MySQL on the target and create it:
Use the same character set and collation as the source to avoid encoding issues.mysql -u root -p -e "CREATE DATABASE dbname CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" - Import the dump on the target server. Run:
This will recreate all tables, data, routines, triggers, and events.mysql -u root -p dbname < /tmp/backup.sql - Verify the import. Compare row counts and table structures between source and target. A quick check:
Run this on both servers and compare. Also spot-check a few tables withmysql -u root -p -e "SELECT table_name, table_rows FROM information_schema.tables WHERE table_schema='dbname';"SELECT COUNT(*). - Test the application against the target. If possible, point a staging environment or a read-only replica to the target server to confirm everything works as expected.
- Switch over. Once you're confident, update your application's database connection settings to point to the target server. If you need to minimize downtime, you can use a reverse proxy or DNS change, but that's beyond the scope of this guide.
- Monitor and clean up. Watch the target server's logs for errors. After a successful switch, you can remove the backup files from both servers if you no longer need them.
Common Mistakes
- Not using
--single-transactionwith InnoDB. Without it, you might get inconsistent data if writes occur during the dump. - Forgetting to include routines, triggers, and events. If your database uses stored procedures or triggers, they won't be in the dump unless you add
--routines,--triggers, and--events. - Ignoring character set differences. If the target database has a different default character set, text data can get corrupted. Always specify the same charset/collation.
- Transferring over an insecure channel. Using plain FTP or HTTP exposes your data. Always use SSH-based methods like
scporrsync. - Not testing the import before switching. Skipping verification can lead to broken applications and data loss.
Tips
- Use
--opt(default) for a faster dump. It enables several optimizations like--quickand--add-drop-table. - Compress the dump file.
gzipcan reduce transfer time significantly for large databases. - Consider using
--hex-blobif you have binary data. This ensures binary columns are dumped in a portable hex format. - Run the import with
--disable-foreign-key-checksto speed it up. AddSET FOREIGN_KEY_CHECKS=0;at the top of the import command or usemysql --init-command="SET FOREIGN_KEY_CHECKS=0;". - Take a fresh backup on the target after the import. This gives you a clean restore point if something goes wrong later.
Troubleshooting
- Import fails with "ERROR 1049 (42000): Unknown database". The target database doesn't exist. Create it first with the correct name and charset.
- Import fails with "ERROR 1064 (42000): You have an error in your SQL syntax". This often happens when the dump was created with a newer MySQL version. Try using
mysql --forceto skip errors, but investigate each one—some may indicate data loss. - Import is extremely slow. Disable foreign key checks and use
--extended-insert(default) to batch inserts. Also, consider increasingmax_allowed_packeton the target server. - Data appears garbled (mojibake). The character set mismatch is the likely culprit. Re-import with the correct charset, or convert the dump file's encoding before importing.
- Triggers or events are missing after import. Ensure you included
--triggersand--eventsin the dump command. If not, you'll need to re-dump with those flags.
Frequently Asked Questions
Can I migrate without downtime?
Yes, if you use a replication setup (e.g., MySQL master-slave) or tools like Percona XtraBackup for live snapshots. The mysqldump method with --single-transaction allows writes during the dump, but the dump itself is a point-in-time snapshot, so you'll need to replay any changes after the dump before switching.
What's the difference between mysqldump and physically copying the data directory?
mysqldump creates a logical backup (SQL statements) that is portable across MySQL versions and platforms. Copying the data directory (e.g., /var/lib/mysql) is faster but requires the target to have the exact same MySQL version and OS architecture, and the server must be stopped to ensure consistency.
How do I migrate only specific tables?
You can specify table names after the database name: mysqldump dbname table1 table2 > backup.sql. This is useful for partial migrations.
Should I use --single-transaction or --lock-tables?
If your tables are InnoDB, use --single-transaction—it gives a consistent snapshot without locking. For MyISAM, you need --lock-tables (which is default) to prevent data changes during the dump.
How can I verify the data integrity after migration?
Compare checksums: run CHECKSUM TABLE on both servers for each table. Alternatively, compare row counts and sample a few rows. For critical data, consider using a tool like pt-table-checksum.
What if the target server has a different MySQL version?
You can usually migrate from an older to a newer version, but the reverse may cause issues. Always check the MySQL upgrade documentation. The dump file may contain syntax that is not compatible with the older version.