Setup Master-Slave Replication in MySQL Server

MySQL replication allows you to have multiple copies of data on many systems and data is automatically copied from one database (Master) to another database (Slave). If one server goes down, the clients still can access the data from another (Slave) server database.

In this article, let us see how to configure MySQL Master-Slave replication. I am using the following two systems to in this how-to:

MySQL Master system : CentOS 6.4
Master IP Address : 192.168.1.250/24
MySQL Slave system : CentOS 6.4
IP Address: 192.168.1.150/24

Setting up MySQL Master

Adjust iptables to allow 3306 port:

[root@server ~]# vi /etc/sysconfig/iptables
# Firewall configuration written by system-config-firewall
# Manual customization of this file is not recommended.
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p udp -m state --state NEW --dport 3306 -j ACCEPT
-A INPUT -p tcp -m state --state NEW --dport 3306 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT

Save and restart iptables:

root@server ~]# service iptables restart

Now install MySQL packages using the following command:

[root@server ~]# yum install mysql-server mysql -y

Start mysqld service.

[root@server ~]# service mysqld start
[root@server ~]# chkconfig mysqld on

Setup MySQL Root password:

[root@server ~]# /usr/bin/mysql_secure_installation
NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL
 SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MySQL to secure it, we'll need the current
 password for the root user.  If you've just installed MySQL, and
 you haven't set the root password yet, the password will be blank,
 so you should just press enter here.

Enter current password for root (enter for none):
 OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MySQL
 root user without the proper authorisation.

Set root password? [Y/n] y
New password:
Re-enter new password:
Password updated successfully!
Reloading privilege tables..
... Success!

By default, a MySQL installation has an anonymous user, allowing anyone
 to log into MySQL without having to have a user account created for
 them.  This is intended only for testing, and to make the installation
 go a bit smoother.  You should remove them before moving into a
 production environment.

Remove anonymous users? [Y/n]
... Success!
Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n]
... Success!

By default, MySQL comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n]
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
 will take effect immediately.

Reload privilege tables now? [Y/n]
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MySQL
installation should now be secure.

Thanks for using MySQL!

Configure MySQL Master

Open /etc/my.cnf file and add the following lines under [mysqld] section:

[root@server ~]# vi /etc/my.cnf
[mysqld]
server-id = 1
binlog-do-db=unixmen
expire-logs-days=7
relay-log = /var/lib/mysql/mysql-relay-bin
relay-log-index = /var/lib/mysql/mysql-relay-bin.index
log-error = /var/lib/mysql/mysql.err
master-info-file = /var/lib/mysql/mysql-master.info
relay-log-info-file = /var/lib/mysql/mysql-relay-log.info
log-bin = mysql-bin

datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

Here unixmen is the database name to be replicated to the Slave system.

Once you are done, restart MySQL service:

[root@server ~]# service mysqld restart
Stopping mysqld:                                           [  OK  ]
Starting mysqld:                                           [  OK  ]

Now login to MySQL and create a Slave user and password. For instance, we will use sk as Slave username and centos as password:

[root@server ~]# mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.1.69-log Source distribution

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
 affiliates. Other names may be trademarks of their respective
 owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> STOP SLAVE;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> GRANT REPLICATION SLAVE ON *.* TO 'sk'@'%' IDENTIFIED BY 'centos';
Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH TABLES WITH READ LOCK;
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW MASTER STATUS;
 +------------------+----------+--------------+------------------+
 | File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
 +------------------+----------+--------------+------------------+
 | mysql-bin.000001 |      106 | unixmen      |                  |
 +------------------+----------+--------------+------------------+
 1 row in set (0.01 sec)

mysql> exit
Bye

Note down the file(mysql-bin.000001) and position number (106), you may need these values later.

Backup Master server database

Enter the following command to dump all Master databases and save them. We will transfer these databases to Slave server later:

[root@server ~]# mysqldump --all-databases --user=root --password --master-data > masterdatabase.sql

This will create a file called masterdatabase.sql. This will take some time depending upon the databases size.

Again login to MySQL as root user and unlock the tables:

[root@server ~]# mysql -u root -p
 Enter password:
 Welcome to the MySQL monitor.  Commands end with ; or \g.
 Your MySQL connection id is 4
 Server version: 5.1.69-log Source distribution

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
 affiliates. Other names may be trademarks of their respective
 owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> UNLOCK TABLES;
Query OK, 0 rows affected (0.01 sec)

mysql> quit
Bye

Copy the masterdatabase.sql file to your Slave server. Here, I copy this file to /home folder. So the command should be:

[root@server ~]# scp masterdatabase.sql root@192.168.1.150:/home
root@192.168.1.150's password: 
masterdatabase.sql                            100%  507KB 506.7KB/s   00:00

Setting up MySQL Slave

We have done Master side installation. Now we have to start on Slave side. Install MySQL packages on Slave server:

[root@server ~]# yum install mysql-server mysql -y

Start mysqld service:

[root@server ~]# service mysqld start
[root@server ~]# chkconfig mysqld on

Seting up MySQL Root password:

[root@server ~]# /usr/bin/mysql_secure_installation
NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL
 SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MySQL to secure it, we'll need the current
 password for the root user.  If you've just installed MySQL, and
 you haven't set the root password yet, the password will be blank,
 so you should just press enter here.

Enter current password for root (enter for none):
 OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MySQL
 root user without the proper authorisation.

Set root password? [Y/n] y
New password:
Re-enter new password:
Password updated successfully!
Reloading privilege tables..
... Success!

By default, a MySQL installation has an anonymous user, allowing anyone
 to log into MySQL without having to have a user account created for
 them.  This is intended only for testing, and to make the installation
 go a bit smoother.  You should remove them before moving into a
 production environment.

Remove anonymous users? [Y/n]
... Success!
Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n]
... Success!

By default, MySQL comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n]
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
 will take effect immediately.

Reload privilege tables now? [Y/n]
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MySQL
installation should now be secure.

Thanks for using MySQL!

Configure MySQL Slave

Open the file /etc/my.cnf and add the following entries under [mysqld] section as shown below. Replace the database name and master server IP Address with your own:

[root@server ~]# vi /etc/my.cnf 
[mysqld]
server-id = 2     
master-host=192.168.1.250  
master-connect-retry=60
master-user=sk
master-password=centos
replicate-do-db=unixmen
relay-log = /var/lib/mysql/mysql-relay-bin
relay-log-index = /var/lib/mysql/mysql-relay-bin.index
log-error = /var/lib/mysql/mysql.err
master-info-file = /var/lib/mysql/mysql-master.info
relay-log-info-file = /var/lib/mysql/mysql-relay-log.info
log-bin = mysql-bin
[...]

Here 192.168.1.200 is Master server IP address, sk is Master server database user, centos is password of user sk, unixmen is Master database name.

Save and exit the file.

Import the master database:

[root@server ~]# mysql -u root -p < /home/masterdatabase.sql 
Enter password:
[root@server ~]# service mysqld restart
Stopping mysqld:                                           [  OK  ]
Starting mysqld:                                           [  OK  ]

Now log in to MySQL as root user and tell the Slave server to where to look for Master log file which is we have created on Master server using the command SHOW MASTER STATUS; (File – mysql-bin.000001 and Position – 106). Make sure that you changed the Master server IP address, username and password as your own:

[root@server ~]# mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 5
Server version: 5.1.69-log Source distribution

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> SLAVE STOP;
Query OK, 0 rows affected (0.01 sec)

mysql> CHANGE MASTER TO MASTER_HOST='192.168.1.250', MASTER_USER='sk', MASTER_PASSWORD='centos', MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=106;
Query OK, 0 rows affected (0.03 sec)

mysql> SLAVE START;
Query OK, 0 rows affected (0.01 sec)

mysql> SHOW SLAVE STATUS\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.1.250
                  Master_User: sk
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000002
          Read_Master_Log_Pos: 106
               Relay_Log_File: mysql-relay-bin.000003
                Relay_Log_Pos: 251
        Relay_Master_Log_File: mysql-bin.000002
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: unixmen
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 106
              Relay_Log_Space: 551
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 0
               Last_SQL_Error: 
1 row in set (0.00 sec)

Test MySQL Replication

Master side:

[root@server ~]# mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.1.69-log Source distribution

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> create database unixmen;
Query OK, 1 row affected (0.04 sec)

mysql> use unixmen;
Database changed

mysql> create table sample (c int);
Query OK, 0 rows affected (0.08 sec)

mysql> insert into sample (c) values (1);
Query OK, 1 row affected (0.01 sec)

mysql> select * from sample;
+------+
| c    |
+------+
|    1 |
+------+
1 row in set (0.01 sec)

mysql>

Slave side:

[root@server ~]# mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 5.1.69-log Source distribution

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use unixmen;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> select * from sample;
+------+
| c    |
+------+
|    1 |
+------+
1 row in set (0.01 sec)

mysql>

That’s it. Now the tables created in the Master server are automatically replicated to the Slave server.