2022-05-20 21:24:09 +02:00
---
2023-02-23 14:48:51 +01:00
title: "MariaDB Replication"
2022-11-19 15:25:20 +01:00
visible: true
2022-05-20 21:24:09 +02:00
---
2022-06-06 18:38:13 +02:00
[toc]
2023-02-23 14:48:51 +01:00
2022-05-20 21:24:09 +02:00
## Master Slave Setup
2023-02-23 14:48:51 +01:00
2022-05-20 21:24:09 +02:00
### Master Configuration
2023-02-23 14:48:51 +01:00
2022-05-20 21:24:09 +02:00
The MariaDB Server has to be accessible from outside. For Debian, one has to comment `bind-address=127.0.0.1` in the file `/etc/mysql/mariadb.conf.d/50-server.cnf` .
2023-02-23 14:48:51 +01:00
If you have any firewall enabled, make sure to allow port 3306/TCP.
2022-05-20 21:24:09 +02:00
2023-02-23 14:48:51 +01:00
Add this segment at the end of `/etc/mysql/my.cnf`
```ini
2022-05-20 21:24:09 +02:00
[mariadb]
log-bin
server_id=1
log-basename=master
binlog-format=mixed
```
2023-02-23 14:48:51 +01:00
**Restart mariadb** now
2022-05-20 21:24:09 +02:00
Create a replication user
2023-02-23 14:48:51 +01:00
```sql
2022-05-20 21:24:09 +02:00
CREATE USER 'replication'@'%' IDENTIFIED BY '< password > ';
GRANT REPLICATION SLAVE ON *.* TO 'replication'@'%';
```
2023-02-23 14:48:51 +01:00
Next we have to get the data necessary so the slave knows where to start replicating.
```sql
FLUSH TABLES WITH READ LOCK;
SHOW MASTER STATUS;
```
2022-05-20 21:24:09 +02:00
**Do not close this session, keep it running until you have made the backup from the next step**
2023-02-23 14:48:51 +01:00
`# mysqldump -u root -p (db name) > db_name.sql`
2022-05-20 21:24:09 +02:00
You can unlock the database again.
2023-02-23 14:48:51 +01:00
`UNLOCK TABLES;`
2022-05-20 21:24:09 +02:00
### Slave Configuration
2023-02-23 14:48:51 +01:00
2022-05-20 21:24:09 +02:00
Edit your `/etc/mysql/my.cnf` file
2023-02-23 14:48:51 +01:00
Make sure to choose different IDs for every host
```ini
2022-05-20 21:24:09 +02:00
[mysqld]
server-id = 2
```
Create the database and restore the sql dumps made earlier.
2023-02-23 14:48:51 +01:00
`# mysql -u root -p (db name) < db_name.sql`
2022-05-20 21:24:09 +02:00
2023-02-23 14:48:51 +01:00
Set the database master now
```sql
2022-05-20 21:24:09 +02:00
CHANGE MASTER TO
MASTER_HOST='< domain > ',
MASTER_USER='replication',
MASTER_PASSWORD='< password > ',
MASTER_PORT=3306,
MASTER_LOG_FILE='< master log file > ',
MASTER_LOG_POS=< master log position > ,
MASTER_CONNECT_RETRY=10,
MASTER_USE_GTID = slave_pos;
```
Start slave now
`START SLAVE;`
And check the status
2023-02-23 14:48:51 +01:00
`SHOW SLAVE STATUS \G`
If both of the following options say yes, everything is working as intended
2022-05-20 21:24:09 +02:00
```
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
2022-11-19 15:25:20 +01:00
```