Hosting & DeploymentHow to Migrate a MySQL Database Between Servers: 7 Powerful & Easy Steps By Team CJ August 14, 202623 viewsShareTweet 0How to Migrate a MySQL Database Between Servers is an important skill for developers, system administrators, DevOps engineers, database administrators, and beginners who manage applications running on MySQL.A MySQL database may need to be moved when you change hosting providers, upgrade your server, move an application to a new environment, migrate from development to production, or replace an old server with a newer one.A database migration means transferring the database structure and data from a source MySQL server to a target MySQL server while keeping the information accurate and usable.The most common beginner-friendly method is to create a logical SQL dump using mysqldump, transfer that dump file to the new server, create the target database, and load the SQL file using the mysql client. MySQL’s official documentation describes this as a standard method for copying databases between machines.If you are new to database administration, How to Migrate a MySQL Database Between Servers may initially sound complicated. However, the basic process is straightforward:Source MySQL Server | | Export database v SQL Dump File | | Transfer file v Target MySQL Server | | Create database | | Import SQL dump v Migrated Database In this tutorial, you will learn How to Migrate a MySQL Database Between Servers using mysqldump and the MySQL client. You will also learn how to migrate large databases, transfer compressed dumps, verify the migration, handle different database names, troubleshoot common errors, and choose alternative migration methods.What Is a MySQL Database Migration?Before learning How to Migrate a MySQL Database Between Servers, it is important to understand what database migration means.A MySQL database migration is the process of moving database structures and data from one MySQL environment to another.For example:Source Server: 192.0.2.10 Database: company_db could be migrated to:Target Server: 192.0.2.20 Database: company_db The database may contain:TablesRowsIndexesViewsStored proceduresFunctionsTriggersEventsConstraintsApplication dataA logical migration with mysqldump converts database contents into SQL statements. Those statements can then be transferred and executed on the target server. MySQL documents mysqldump as a tool for producing SQL-format dumps that can be reloaded with the mysql client.Why Migrate a MySQL Database Between Servers?There are many reasons to learn How to Migrate a MySQL Database Between Servers.Common situations include:Changing Hosting ProvidersYou may move an application from one hosting company to another.Upgrading Server HardwareA database may need to be moved to a server with:More RAMFaster storageMore CPUBetter networkingMoving From Development to ProductionDevelopers often create databases in development and later migrate the required data to production.Moving to Cloud InfrastructureA company may move an existing MySQL installation to a cloud server.Disaster RecoveryA database can be transferred to another server as part of a recovery plan.Server ReplacementOlder servers may need to be replaced while keeping application data.Database ConsolidationMultiple applications may be reorganized onto new infrastructure.Understanding How to Migrate a MySQL Database Between Servers gives you a repeatable method for these situations.What You Need Before StartingBefore beginning How to Migrate a MySQL Database Between Servers, prepare both servers.You should have access to the source server and target server.Source ServerYou need:MySQL accessDatabase nameDatabase usernameDatabase passwordPermission to create a database dumpEnough disk space if creating a dump file locallyTarget ServerYou need:MySQL or a compatible target serverDatabase creation privilegesDatabase usernameDatabase passwordEnough storagePermission to import the databaseFile Transfer MethodYou also need a way to transfer the dump file.Common options include:scpSFTPFTPrsyncCloud storageSecure internal network transferFor a Linux-to-Linux migration, scp is often convenient.How to Migrate a MySQL Database Between Servers Step by StepNow let’s learn How to Migrate a MySQL Database Between Servers using a practical example.Assume the source server contains:Database: company_db The target server will also use:Database: company_db The source server is:192.0.2.10 The target server is:192.0.2.20 These are example addresses. Replace them with your actual server information.Step 1: Check the MySQL VersionsThe first step in How to Migrate a MySQL Database Between Servers is checking the MySQL version on both systems.On the source server, run:mysql --version You can also connect to MySQL and run:SELECT VERSION(); Then check the target server.Try to understand whether you are moving between:The same MySQL versionDifferent MySQL versionsDifferent major versionsMySQL and another compatible database systemVersion compatibility matters because database features and behavior can differ between releases.MySQL’s current documentation provides supported upgrade paths and recommends reviewing compatibility before moving between releases.For a straightforward migration, using compatible versions reduces unexpected problems.Step 2: Create a Backup Before MigrationBefore learning How to Migrate a MySQL Database Between Servers, create a backup.Do not treat the migration dump as your only backup.Create a separate backup copy and keep it somewhere safe.MySQL’s documentation emphasizes the importance of backups for recovery and for transferring installations to another system.For example:mysqldump -u root -p company_db > company_db_backup.sql You will be asked for the MySQL password.After the command finishes, check the file:ls -lh company_db_backup.sql You should see the dump file.For example:-rw-r--r-- 1 user user 250M company_db_backup.sql Keep this backup until the migration has been successfully verified.Step 3: Export the MySQL DatabaseThis is one of the most important steps in How to Migrate a MySQL Database Between Servers.Use mysqldump to create a logical SQL dump.A basic command is:mysqldump -u root -p company_db > company_db.sql After entering the password, MySQL writes SQL statements into:company_db.sql The dump can contain statements needed to recreate the database objects and data.MySQL officially documents the basic pattern:mysqldump db_name > dump.sql followed by loading the dump into the target database.Export With Useful OptionsFor many InnoDB-based applications, a more practical command is:mysqldump \ -u root \ -p \ --single-transaction \ --routines \ --events \ --triggers \ company_db > company_db.sql Let’s understand these options.--single-transactionThis option is useful for transactional tables such as InnoDB because it can produce a consistent logical backup without locking tables in the same way as some other approaches.MySQL documents --single-transaction as an online backup option for InnoDB tables.It is not a universal solution for every storage engine or workload, so understand your database before relying on it for consistency.--routinesThis includes stored procedures and functions.--eventsThis includes MySQL events.--triggersThis includes triggers.Review your MySQL version and application requirements before selecting dump options.Step 4: Compress the Database DumpIf the database is large, compressing the dump can significantly reduce the size of the file that needs to be transferred.For example:mysqldump \ -u root \ -p \ --single-transaction \ --routines \ --events \ --triggers \ company_db | gzip > company_db.sql.gz Check the resulting file:ls -lh company_db.sql.gz You may see:company_db.sql.gz Compression is especially useful when the database contains a lot of repetitive text data.MySQL’s official documentation also demonstrates creating a compressed dump and then loading it on another machine.How to Migrate a MySQL Database Between Servers Using a Dump FileAfter creating the dump, you need to move it to the target server.This is the next important stage of How to Migrate a MySQL Database Between Servers.Step 5: Transfer the Dump FileIf you are using Linux servers, scp is a simple option.For an uncompressed dump:scp company_db.sql user@192.0.2.20:/home/user/ For a compressed dump:scp company_db.sql.gz user@192.0.2.20:/home/user/ Replace:user with the appropriate target-server user.Replace:192.0.2.20 with the actual target server address.After transferring the file, connect to the target server:ssh user@192.0.2.20 Then check:ls -lh You should see your dump file.Alternative: Transfer the Database DirectlyFor smaller or controlled environments, MySQL documents a direct source-to-target approach where mysqldump output is piped into the mysql client on another server.Conceptually:mysqldump company_db | mysql -h target-server company_db However, this method requires the target server to be reachable and configured to accept the connection.For beginners, creating a dump file first is often easier because you have a file that can be inspected, transferred, backed up, and reused.Step 6: Create the Database on the Target ServerThe next step in How to Migrate a MySQL Database Between Servers is creating the destination database.Log in to MySQL on the target server:mysql -u root -p Create the database:CREATE DATABASE company_db; Check it:SHOW DATABASES; You should see:company_db You can also specify a character set and collation when creating a new database if your application requires particular settings:CREATE DATABASE company_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; Choose settings that are compatible with your existing application and database.Create a Dedicated Database UserAvoid using the MySQL root account for your application.Create a dedicated user:CREATE USER 'company_user'@'localhost' IDENTIFIED BY 'StrongPasswordHere'; Grant the required permissions:GRANT ALL PRIVILEGES ON company_db.* TO 'company_user'@'localhost'; Then:FLUSH PRIVILEGES; Your application can then connect using:Database: company_db Username: company_user Password: StrongPasswordHere Use a strong, unique password.Do not place database credentials in publicly accessible files or source-control repositories.How to Migrate a MySQL Database Between Servers With a Different Database NameSometimes the source database is:old_company_db while the target database should be:new_company_db This is still possible.Create the target database:CREATE DATABASE new_company_db; Then import the dump into the new database:mysql -u root -p new_company_db < old_company_db.sql MySQL documents that omitting the --databases option from mysqldump allows you to load a dump into a database with a different name, provided you create the destination database first.This is useful when changing database names during an application migration.Step 7: Import the DatabaseNow we reach the main destination step in How to Migrate a MySQL Database Between Servers.If your dump is:company_db.sql run:mysql -u root -p company_db < company_db.sql Enter the target MySQL password.If the import is successful, the command may return to the shell without displaying a success message.That is normal.You can then log in:mysql -u root -p Select the database:USE company_db; List the tables:SHOW TABLES; You should see the migrated tables.Import a Compressed DumpIf you created:company_db.sql.gz you can import it using:gunzip < company_db.sql.gz | mysql -u root -p company_db This avoids creating a second uncompressed copy on disk.MySQL’s documentation provides the same general pattern for loading compressed dumps on another machine.How to Verify the Migrated MySQL DatabaseVerification is a critical part of How to Migrate a MySQL Database Between Servers.Do not assume that a successful import means the migration is complete.Check the database carefully.Check the TablesRun:USE company_db; SHOW TABLES; Compare the table list with the source database.Check the Number of TablesYou can count tables with:SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'company_db'; Compare the result with the source server.Check Important Row CountsFor example:SELECT COUNT(*) FROM users; Then compare the result between the source and target servers.Repeat for important tables.For example:SELECT COUNT(*) FROM orders; SELECT COUNT(*) FROM products; SELECT COUNT(*) FROM customers; This can help identify missing data.Check Database SizeYou can estimate database size using:SELECT table_schema AS database_name, ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS size_mb FROM information_schema.tables WHERE table_schema = 'company_db' GROUP BY table_schema; Compare the approximate size between the two servers.A difference does not automatically mean data is missing because storage and index structures can vary.Check ViewsIf your application uses views, verify them:SHOW FULL TABLES WHERE Table_type = 'VIEW'; Make sure the expected views exist.Check Stored Procedures and FunctionsRun:SHOW PROCEDURE STATUS WHERE Db = 'company_db'; For functions:SHOW FUNCTION STATUS WHERE Db = 'company_db'; If you intentionally exported routines using --routines, verify that they were imported.Check EventsIf your application uses scheduled MySQL events:SHOW EVENTS FROM company_db; Confirm that expected events exist.How to Migrate a MySQL Database Between Servers With Minimal DowntimeFor applications that receive constant traffic, downtime can be a major concern.A simple dump-and-restore process can create a period where the source database changes after the dump begins.For example:10:00 AM Start dump 10:05 AM Application writes new data 10:10 AM Dump finishes 10:15 AM Import starts The target server may not contain changes made after those rows were captured.For a small application, you may be able to schedule a maintenance window.For larger systems, more advanced approaches may be appropriate.ReplicationMySQL replication can keep a target server updated from a source server.You can then switch applications to the new server after synchronization.MySQL documents replication as one strategy for maintaining identical data across servers and for supporting migration or backup workflows.Maintenance ModeFor applications that cannot tolerate inconsistent data, temporarily stop writes during the final migration.For example:Enable maintenance mode ↓ Stop application writes ↓ Create final database dump ↓ Transfer dump ↓ Import database ↓ Test application ↓ Switch application ↓ Disable maintenance mode This is simpler than replication for many small websites.How to Migrate a Large MySQL Database Between ServersWhen learning How to Migrate a MySQL Database Between Servers, you may eventually need to move a database that is several gigabytes or larger.Large databases require additional planning.Use CompressionUse:mysqldump -u root -p --single-transaction company_db | gzip > company_db.sql.gz This reduces transfer size when the data compresses well.Use a Fast Transfer MethodFor large files, consider:rsyncSFTPSecure internal network transferDedicated storageCloud object storageConsider MySQL ShellModern MySQL environments can also use MySQL Shell dump and load utilities.MySQL documents MySQL Shell as an alternative to mysqldump, with features such as parallel dumping, compression, progress information, and cloud-related capabilities.For very large databases, MySQL Shell may be more efficient than a simple single-threaded logical dump.Consider ReplicationIf downtime must be very low, replication may be more appropriate than a traditional dump-and-import process.How to Migrate a MySQL Database Between Servers Using MySQL ShellFor larger environments, MySQL Shell provides dump and load utilities.The exact commands depend on your MySQL Shell version and deployment requirements.The general workflow is:Source MySQL Server | v MySQL Shell Dump | v Dump Directory | | Transfer v Target Server | v MySQL Shell Load MySQL’s current documentation recommends considering MySQL Shell dump utilities because they support parallel dumping, compression, progress information, and other features.For a beginner with a small database, however, mysqldump remains easier to understand and is an excellent starting point.Common Errors During MySQL MigrationEven after following How to Migrate a MySQL Database Between Servers, you may encounter errors.Access Denied for UserYou may see:ERROR 1045 (28000): Access denied for user Check:UsernamePasswordHostUser privilegesAuthentication configurationTest the credentials:mysql -u company_user -p Unknown DatabaseYou may see:ERROR 1049 (42000): Unknown database Create the database first:CREATE DATABASE company_db; Then import:mysql -u root -p company_db < company_db.sql Table Already ExistsYou may see:ERROR 1050: Table already exists This usually means the target database already contains tables.If the target database is intended to be replaced completely, carefully remove the old data before importing.Do not delete production data without a verified backup.Duplicate Entry ErrorsYou may see:ERROR 1062: Duplicate entry This can happen if the target database already contains some of the same records.Check whether the target database is empty before importing.Unknown CollationDuring migration between different MySQL versions, you may encounter errors related to character sets or collations.For example, a dump generated by a newer version may contain a collation that the target server does not recognize.Check the source and target MySQL versions before migrating.If necessary, review the dump and compatibility requirements rather than blindly replacing collation names.Packet Too LargeSome applications may encounter errors related to packet size when importing large rows or statements.Check the relevant MySQL configuration, including:max_allowed_packet You can inspect it with:SHOW VARIABLES LIKE 'max_allowed_packet'; If you need to change server configuration, make the change according to your MySQL version and hosting environment.Check Character Sets and CollationsCharacter sets are important when learning How to Migrate a MySQL Database Between Servers.A website may contain:EnglishArabicHindiUrduChineseEmojiOther Unicode charactersFor modern applications, utf8mb4 is commonly used.Check the database:SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = 'company_db'; Also check individual tables if necessary.Incorrect character-set handling can cause:Broken charactersQuestion marksImport errorsIncorrect sortingAlways consider the application’s existing character-set requirements before changing them during migration.Update the Application ConfigurationAfter completing How to Migrate a MySQL Database Between Servers, your application must connect to the new database server.For a PHP application, you may have configuration such as:$db_host = "localhost"; $db_name = "company_db"; $db_user = "company_user"; $db_password = "YOUR_PASSWORD"; Update the values according to the target environment.For a Node.js application, the configuration may use environment variables:DB_HOST=127.0.0.1 DB_PORT=3306 DB_NAME=company_db DB_USER=company_user DB_PASSWORD=YOUR_PASSWORD Do not commit passwords or other secrets to Git repositories.If the application runs on a different server from MySQL, the target MySQL server must also be configured to accept the required network connection securely.Test the Application After MigrationThe database migration is not finished until the application works.Test:LoginRegistrationUser profilesSearchProduct pagesOrdersPaymentsReportsAdmin dashboardAPI requestsBackground jobsScheduled tasksFile uploadsDatabase writesCreate a test record:Test User Then verify it appears correctly in the database.You can also test an update and deletion operation if your environment allows it.Security Best Practices for MySQL MigrationSecurity should always be part of How to Migrate a MySQL Database Between Servers.Use Secure File TransferPrefer:SCP SFTP rsync over SSH instead of insecure file-transfer methods.Protect the SQL DumpA database dump may contain sensitive information.It can include:User informationEmail addressesApplication dataInternal recordsPassword hashesTokensBusiness informationTreat the dump as sensitive data.Delete Temporary Dumps When FinishedAfter verifying the migration, securely remove temporary files that are no longer required.For example:rm company_db.sql Only remove the file after confirming that your backup requirements have been satisfied.Use Strong Database PasswordsCreate unique credentials for the target environment.Restrict Network AccessIf the application and MySQL server are separate machines, allow only the required application server or network to access MySQL.Do not expose MySQL publicly without a strong reason and appropriate security controls.Best Practices for MySQL Database MigrationWhen learning How to Migrate a MySQL Database Between Servers, follow these practices.1. Back Up Before StartingAlways create a verified backup.2. Check MySQL VersionsKnow the source and target versions.3. Test the DumpMake sure the dump file was created successfully.4. Use Compression for Large DumpsUse gzip when appropriate.5. Transfer Files SecurelyUse SSH-based transfer methods.6. Create the Target Database CarefullyUse the correct database name, character set, and collation.7. Verify PermissionsMake sure the application database user has the required permissions.8. Verify DataCompare important row counts and tables.9. Test the ApplicationDo not stop after checking only the database.10. Keep the Original DatabaseDo not immediately destroy the source environment.Useful MySQL Migration CommandsHere are the most useful commands to remember when learning How to Migrate a MySQL Database Between Servers.Check MySQL Versionmysql --version Export Databasemysqldump -u root -p company_db > company_db.sql Export With Transactionmysqldump -u root -p --single-transaction company_db > company_db.sql Export and Compressmysqldump -u root -p --single-transaction company_db | gzip > company_db.sql.gz Transfer With SCPscp company_db.sql user@TARGET_SERVER:/home/user/ Create DatabaseCREATE DATABASE company_db; Import Databasemysql -u root -p company_db < company_db.sql Import Compressed Dumpgunzip < company_db.sql.gz | mysql -u root -p company_db Show TablesUSE company_db; SHOW TABLES; Check Database SizeSELECT table_schema, ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS size_mb FROM information_schema.tables WHERE table_schema = 'company_db' GROUP BY table_schema; Internal ResourcesFor related database and development tutorials, you can connect this article with relevant content on CodexJunction.A useful internal resource is the CodexJunction Tutorials section, where readers can continue learning about programming, databases, web development, and server-related technologies. CodexJunction TutorialsCodexJunction also has MySQL-related content, including an article about sorting MySQL results using LIKE, which can be useful for readers who want to continue learning MySQL queries. MySQL Tutorials on CodexJunctionYou can also add internal links to your own related articles such as:How to Troubleshoot a MySQL Database ConnectionHow to Create a MySQL DatabaseHow to Back Up a Website DatabaseHow to Configure Apache Virtual HostsHow to Migrate a WordPress Website ManuallyMake sure these are linked to the actual published URLs of the corresponding articles on your website.External ResourcesFor authoritative information, readers should refer to the official MySQL documentation.MySQL: Copying Databases to Another MachineThis official guide explains how to use mysqldump, transfer a dump file, and load the database on another machine. MySQL — Copying Databases to Another MachineMySQL: Using mysqldumpThe official mysqldump documentation explains how to create SQL-format database dumps and use different dump options. MySQL — Using mysqldump for BackupsMySQL: Reloading SQL-Format BackupsThis guide explains how to import SQL-format dumps using the MySQL client. MySQL — Reloading SQL-Format BackupsMySQL: Database Backup MethodsThis documentation explains logical backups, physical backups, mysqldump, binary logs, and other backup strategies. MySQL — Database Backup MethodsMySQL: Upgrade PathsIf your migration also involves moving between MySQL versions, review the official upgrade-path documentation before proceeding. MySQL — Upgrade PathsFrequently Asked QuestionsHow to Migrate a MySQL Database Between Servers?To learn How to Migrate a MySQL Database Between Servers, create a database dump using mysqldump, transfer the dump to the target server, create the destination database, import the SQL file, verify the data, and update the application connection settings.What is the easiest way to migrate a MySQL database?For many small and medium databases, mysqldump is one of the easiest methods. It creates a logical SQL dump that can be transferred and loaded on another MySQL server. MySQL officially documents this approach for copying databases between machines.Can I migrate MySQL without stopping the server?For InnoDB-heavy workloads, mysqldump --single-transaction can create an online logical backup without locking tables in the same way as some other methods. However, the exact consistency guarantees depend on the storage engines and workload.Can I migrate a MySQL database to a different server IP?Yes. The database itself does not depend on the server IP in the normal dump-and-restore process. After importing the database, update the application configuration so it connects to the new MySQL host.Can I use a different database name on the new server?Yes. Create the new database and load a single-database dump into it. MySQL documents this approach when the --databases option is omitted from mysqldump.Can I migrate a large MySQL database?Yes. For large databases, consider compression, efficient file transfer, MySQL Shell dump utilities, or replication depending on database size and downtime requirements. MySQL documents MySQL Shell dump utilities as an option with parallel dumping and compression capabilities.How do I migrate MySQL with minimal downtime?For a small application, you can use a maintenance window and perform a final dump before switching the application. For larger systems, replication can help keep the target server synchronized before the final cutover.What happens if the MySQL versions are different?The migration may still work, but compatibility must be checked. Differences in features, SQL syntax, character sets, collations, authentication, and other behavior can cause problems. Review the supported MySQL upgrade and migration paths before moving between major versions.Should I delete the source database after migration?No. Keep the original database and a verified backup until the target database and application have been thoroughly tested.How can I verify that the migration worked?Compare table lists, important row counts, database size, views, routines, events, and application behavior. Then test real application operations such as reading, inserting, updating, and deleting data where appropriate.MySQL Migration ChecklistUse this checklist when following How to Migrate a MySQL Database Between Servers:Check source MySQL version.Check target MySQL version.Create a separate backup.Verify database credentials.Export the source database.Check the dump file size.Compress the dump if necessary.Transfer the dump securely.Create the target database.Create the target database user.Assign required permissions.Import the SQL dump.Check the table list.Compare important row counts.Check views.Check stored procedures and functions.Check scheduled events.Check character sets and collations.Update application database credentials.Test application connectivity.Test important application features.Monitor for errors.Keep the source database until migration is confirmed.Final VerificationAfter completing How to Migrate a MySQL Database Between Servers, perform a final verification.First, confirm that MySQL is running on the target server:sudo systemctl status mysql Then connect:mysql -u company_user -p company_db Run:SHOW TABLES; Check important tables:SELECT COUNT(*) FROM users; Then test your application.If the application successfully connects to the new database and users can perform normal operations, the migration is likely complete.Keep monitoring the target server after the cutover.ConclusionHow to Migrate a MySQL Database Between Servers becomes much easier when you understand the basic migration workflow.The standard process is:1. Check MySQL versions ↓ 2. Back up the source database ↓ 3. Create a mysqldump ↓ 4. Transfer the dump ↓ 5. Create the target database ↓ 6. Import the dump ↓ 7. Verify the data ↓ 8. Update the application ↓ 9. Test everything For many beginner and medium-sized migrations, mysqldump provides a practical logical migration method. MySQL officially documents creating a dump, transferring it to another machine, and loading it with the MySQL client.For larger databases, you may need more advanced solutions such as MySQL Shell dump utilities, replication, or physical backup methods. MySQL’s documentation describes several backup and migration strategies and explains when different approaches may be appropriate.The most important rule when learning How to Migrate a MySQL Database Between Servers is to protect the original data. Always create a verified backup before starting, use secure file-transfer methods, check MySQL version compatibility, verify the imported data, and keep the source database available until the new environment has been tested.With these steps, beginners can confidently understand How to Migrate a MySQL Database Between Servers and use the same workflow when moving databases between development servers, production servers, hosting providers, VPS environments, and cloud infrastructure.
Hosting & DeploymentHow to Configure MX Records for Email: 7 Proven Easy Steps By Team CJAugust 15, 20260
Hosting & DeploymentHow to Add DKIM and DMARC Records: 7 Proven Safe Steps By Team CJAugust 15, 20260