Home   Profile   Fun
#170 Linux  03.03.2009

How to run two independent MySQL daemons on the same server


The goal is to run two independent MySQL daemones at the same time. This can be used to run a database replication if you have only one host. The replicated MySQL databases can then be used to create backups. For consistent backups all tables need a read lock during the backup process so that no data can be written. If you use the live databases for this you may get into conflict with user actions. For that reason the second daemon can be used to create the backup. You can lock its tables and no user will be disturbed. After the backup the replication immediately synchronizes the data with the live databases. Note however that replication does not work via sockets. For replication the MySQL daemons must communicate via TCP/IP and thus need different IPs.

To set up this scenario the MySQL daemons need different ports and different sockets.
I assume there already exists one MySQL server with the configuration file /var/db/mysql/mysql.cnf.
Let's say this file contains the following parameters:
port=3306
datadir=/var/db/mysql
pid-file=/var/db/mysql/mysql.pid
tmpdir=/var/db/tmp
socket=/tmp/mysql.sock

We create a second data directory by copying /var/db/mysql to /var/db/mysql2.
cp -rp /var/db/mysql /var/db/mysql2

We also need a second tmp directory.
cp -rp /var/db/tmp /var/db/tmp2

The new data and tmp directories should have the same permissions as the original ones.
For the second server we change some parameters in the configuration file /var/db/mysql2/mysql.cnf:
port=3307
datadir=/var/db/mysql2
pid-file=/var/db/mysql2/mysql.pid
tmpdir=/var/db/tmp2
socket=/tmp/mysql2.sock

Now we can start both servers:
/usr/local/bin/mysqld_safe --defaults-file=/var/db/mysql/mysql.cnf &
/usr/local/bin/mysqld_safe --defaults-file=/var/db/mysql2/mysql.cnf &

Clients from localhost can access the servers by using the socket files.
mysql -uroot -p -h localhost -S /tmp/mysql.sock
mysql -uroot -p -h localhost -S /tmp/mysql2.sock

Clients from remote machines can access the servers by using the ports.
mysql -uroot -p -h dbserver -P 3306
mysql -uroot -p -h dbserver -P 3307