Thursday, October 29, 2026

Moodle migration to freshly installed server - MySQL database migration

This post is linked from this index post - migrating Moodle instances from Azure VMs to AWS EC2 VMs

Here are the steps suggested by Claude for migrating the MySQL databases for Moodle from our old server on an Azure VM to our new server on AWS EC2. 

1. Create the user. Type the password at the prompt, it won't be echoed.
read -rs DBPASS; echo
sudo mysql -e "CREATE USER 'our_db_admin'@'%' IDENTIFIED BY '$DBPASS';"
unset DBPASS
sudo mysql -e "SELECT user, host, plugin FROM mysql.user WHERE user='our_db_admin';"

Error on create user, if any, is probably because user already exists. If the user is listed with
sudo mysql -e "SELECT user, host, plugin FROM mysql.user WHERE user='our_db_admin';"

just set its password using
read -rs DBPASS; echo
sudo mysql -e "ALTER USER 'our_db_admin'@'%' IDENTIFIED BY '$DBPASS';"
unset DBPASS

2. Create .dump.cnf on old server. A configuration file so that we don't need to type in the password for the many scripts which follow.
nano ~/.dump.cnf
with the contents
[client]
host=127.0.0.1
user=our_db_admin
password=dbpass-VALUE-FROM-config.php-HERE

chmod 600 ~/.dump.cnf

3. Dump all four databases. Run this as normal login user on the new server:
mkdir -p ~/dumps && cd ~/dumps
SSH="ssh -p 2022 -i $HOME/.ssh/migrate_key azureuser@OLD-SERVER-IP"

for db in ourdb1_master_db ourdb2_db ourdb3_master_db ourdb4_master_db; do
  echo "dumping $db ..."
  time $SSH "mysqldump --defaults-extra-file=/home/azureuser/.dump.cnf \
    --single-transaction --quick --routines --triggers --no-tablespaces \
    --databases $db | gzip -c" > $db.sql.gz
done
ls -lh ~/dumps

The dumps went much faster than I expected. Less than two minutes for even the largest db.

dumping ourdb2_master_db ...

real 1m46.508s
user 0m0.419s
sys 0m0.329s

...

total 427M


4. Restore and grant: On the new server.

cd ~/dumps
for f in *.sql.gz; do
  echo "restoring $f ..."
  zcat $f | sudo mysql
done

sudo mysql -e "
GRANT ALL PRIVILEGES ON ourdb1_master_db.*   TO 'our_db1_admin'@'%';
GRANT ALL PRIVILEGES ON ourdb2_master_db.* TO 'our_db2_admin'@'%';
GRANT ALL PRIVILEGES ON ourdb3_master_db.*  TO 'our_db3_admin'@'%';
GRANT ALL PRIVILEGES ON ourdb4_master_db.*   TO 'our_db4_admin'@'%';"

5. Verify. Compare table counts on both servers.
Old server:
mysql --defaults-extra-file=$HOME/.dump.cnf -e "SELECT table_schema, COUNT(*) AS tables FROM information_schema.tables WHERE table_schema LIKE our%' GROUP BY table_schema;"

New server:
sudo mysql -e "SELECT table_schema, COUNT(*) AS tables FROM information_schema.tables WHERE table_schema LIKE our%' GROUP BY table_schema;" 

All was well. The db restores took around 15 minutes for the 4 databases.

No comments:

Post a Comment