MySQL replication: adding a new database

Sometimes, you will see MySQL setups where only one database is being replicated. How to add a second database, so that it’s also replicated?

In my.cnf on both servers, add a second database:

replicate-do-db          = first_db
replicate-do-db          = second_db
binlog-do-db            = first_db
binlog-do-db            = second_db

Connect to mysql on both servers and add a new database:


# mysql -p
mysql> CREATE DATABASE second_db;

Now, restart mysql on both servers and verify that replication works (be careful when restarting if there are any writes to the database; i.e. shutdown the secondary master first, then the primary master – depending on your environment):


mysql> use second_db;
Database changed
mysql> show tables;
Empty set (0.00 sec)
mysql> CREATE TABLE example (
-> id INT,
-> data VARCHAR(100)
-> );
Query OK, 0 rows affected (0.13 sec)
mysql> drop table example;
Query OK, 0 rows affected (0.02 sec)
mysql>

After creating/dropping the example table on one server, verify it’s happening on the second server as well:


mysql> show tables;
+---------------------+
| Tables_in_second_db |
+---------------------+
| example |
+---------------------+
1 row in set (0.00 sec)
mysql> show tables;
Empty set (0.01 sec)

Don’t forget to add a user with proper privileges, i.e.:


mysql> CREATE USER someuser IDENTIFIED BY 'password';
Query OK, 0 rows affected (0.23 sec)
mysql> GRANT ALL ON second_db.* TO 'someuser'@'%';
Query OK, 0 rows affected (0.00 sec)

3 Comments

  1. If only it were that easy to maintain. Once one of the databases goes down, the position of the Master database needs to be locked, recorded, copied to the backup; and then the backup needs to be synced with the master’s position, and the the master needs to be started. If any of this is being interacted with from the web, then those machines webservers should be stopped while doing all of this.

    In short, its not the hardest thing but it is more than this post suggests. Read up on this full chapter of MySQL replication before getting too far into this:
    http://dev.mysql.com/doc/refman/5.1/en/replication.html

  2. in fact, there is more to it that I stated in my first post; sorry I didn’t mention the the first time.

Leave a Reply