Migrating a database is an important step when shifting a website or application from a local development environment to a production server. This guide explains how to migrate a MySQL/MariaDB database from your local machine to a remote server using the command line (CLI).
By following these steps, you will gain a reliable and efficient method of transferring your data while minimising errors.
- Export the Localhost database:
Use the appropriate command based on the database type installed on your local machine.
For MySQL:mysqldump -u local_user -p local_database > local_database.sql
For MariaDB:
mariadb-dump -u local_user -p local_database > local_database.sql
Explanation:
local_user: your local database username
local_database: name of the database you want to export
The database password will be requested from you. - Move the SQL file to the remote server:
Use scp (secure copy) to move the dump file to your remote server.scp local_database.sql user@remote_host:/path/to/destination
- User: your remote server username
- remote_host: server IP or hostname
- /path/to/destination: directory on the remote server where you want to place the file
- Install the database on the remote server:
Log in to your remote server via SSH and run the following command:mysql -u remote_user -p remote_database < /path/to/destination/local_database.sql
- remote_user: remote database username
- remote_database: name of the database where you want to import data
You’ll be prompted for the remote database password.
- Another method:
Alternatively, you can also migrate the database directly without creating a file and simply using a single command:mysqldump -u local_user -p local_database | mysql -u remote_user -p -h remote_host remote_database
- Confirm the Migration:
To confirm successful migration, log in to your remote database and execute the following:mysql -u remote_user -p -h remote_host
Then check available databases, using:
SHOW DATABASES;
Notes & Best Practices
- Always back up the remote database before importing.
- Allow MySQL connections in the firewall if using direct migration (-h remote_host).
- For large databases, compress with gzip before transfer:
mysqldump -u local_user -p local_database | gzip > local_database.sql.gz scp local_database.sql.gz user@remote_host:/path/to/destination gunzip local_database.sql.gz mysql -u remote_user -p remote_database < local_database.sql
By following this guide, you can migrate a MySQL/MariaDB database from your local machine to a remote server via CLI. This process confirms your application data is safely transferred, enabling a smooth transition from development to production. Always keep your credentials secure and verify the migration to avoid data discrepancies.
Migrated your database? Learn How to search and replace in the WordPress database using WP CLI