Skip to content

Instantly share code, notes, and snippets.

@Otienoh
Last active July 18, 2018 16:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Otienoh/5e3fc93a392d70c38e7e3f5cb41a08e0 to your computer and use it in GitHub Desktop.
Save Otienoh/5e3fc93a392d70c38e7e3f5cb41a08e0 to your computer and use it in GitHub Desktop.

How To Set Up Database Replication In MySQL

About MySQL replication

This tutorial describes how to set up database replication in MySQL. MySQL replication allows you to have an exact copy of a database from a master server on another server (slave), and all updates to the database on the master server are immediately replicated to the database on the slave server so that both databases are in sync. This is not a backup policy because an accidentally issued DELETE command will also be carried out on the slave; but replication can help in othe situations

  1. protect against hardware failures as part of your database failover strategy.
  2. Reducing load on production master server by running expensive report queries on the slave server. In these setup, you should only allow accept write queries on the master server, other wise those changes made on a specific slave server won't be replicated across all instances of replication servers.

MySQL Server setup

Consider a very simple example of mysql replication—one master will send information to a single slave.

Configuring the master server

Open up the mysql configuration file on the master server, edit /etc/mysql/my.cnf file

sudo nano /etc/mysql/my.cnf

Define the log file to be used (these logs are used by the slave to see what has changed on the master) and specify that this MySQL server is the master.

### uncomment this line (set it to 1)
server-id = 1

### define binary log location
log_bin = /var/log/mysql/mysql-bin.log

Save and restart MYSQL

sudo service mysql restart

Log into MySQL on the Master MySQL server and create the replication user(the user who will connect to the master server to copy it)

GRANT REPLICATION SLAVE ON *.* TO 'replication_user'@'%' IDENTIFIED BY 'swpassword';
FLUSH PRIVILEGES;

Configure the replica server

Open up the mysql configuration file on the replica server, edit /etc/mysql/my.cnf file

sudo nano /etc/mysql/my.cnf

Define the log file to be used (these logs are used by the slave to see what has changed on the master) and specify a unique server id (I usually just increment), set the relay logm set the binary log

### uncomment this line (set it to 1)
server-id = 2

# define the relay log
relay-log               = /var/log/mysql/mysql-relay-bin.log

### define binary log location
log_bin = /var/log/mysql/mysql-bin.log

Save and restart MYSQL

sudo service mysql restart

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment