Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

MySQL Database Migration Between Two Servers Safely

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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, and RELOAD privileges on the source, and CREATE, INSERT, ALTER, and DROP privileges 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

  1. 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.
  2. Create a backup on the source server. Run the following command, replacing dbname with your database name and backup.sql with your desired filename:
    mysqldump -u root -p --single-transaction --routines --triggers --events dbname > backup.sql
    The --single-transaction flag 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-tables instead (this will briefly lock writes).
  3. Verify the dump file. Check that the file is not empty and look at the first few lines:
    ls -lh backup.sql
    head -n 20 backup.sql
    You should see SQL statements and no error messages.
  4. Transfer the dump to the target server. Use scp or rsync over SSH. For example:
    scp backup.sql user@target-server:/tmp/
    If the file is large, consider compressing it first: gzip backup.sql then transfer the .gz file and decompress on the target.
  5. 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:
    mysql -u root -p -e "CREATE DATABASE dbname CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
    Use the same character set and collation as the source to avoid encoding issues.
  6. Import the dump on the target server. Run:
    mysql -u root -p dbname < /tmp/backup.sql
    This will recreate all tables, data, routines, triggers, and events.
  7. Verify the import. Compare row counts and table structures between source and target. A quick check:
    mysql -u root -p -e "SELECT table_name, table_rows FROM information_schema.tables WHERE table_schema='dbname';"
    Run this on both servers and compare. Also spot-check a few tables with SELECT COUNT(*).
  8. 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.
  9. 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.
  10. 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-transaction with 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 scp or rsync.
  • 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 --quick and --add-drop-table.
  • Compress the dump file. gzip can reduce transfer time significantly for large databases.
  • Consider using --hex-blob if you have binary data. This ensures binary columns are dumped in a portable hex format.
  • Run the import with --disable-foreign-key-checks to speed it up. Add SET FOREIGN_KEY_CHECKS=0; at the top of the import command or use mysql --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 --force to 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 increasing max_allowed_packet on 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 --triggers and --events in 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.