**拉取镜像**
`docker pull mysql:5.6.40`
**运行主和从容器**
`docker run -p 3307:3306 --name mysql-master -e MYSQL_ROOT_PASSWORD=123456 -d mysql:5.6.40`
`docker run -p 3308:3306 --name mysql-slave -e MYSQL_ROOT_PASSWORD=123456 -d mysql:5.6.40`
**进入主容器**
`docker exec -it mysql-master bash`
vi /etc/mysql/my.cnf
增加以下内容(默认是同步所有库)
~~~
[mysqld]
server-id = 1
log_bin = master-bin
~~~
`server mysql restart`
~~~
mysql -uroot -p
mysql>grant replication slave on *.* to '用户名' @'%.%.%.%' identified by '密码';
server mysql restart
~~~
**进入从容器**
`docker exec -it mysql-slave bash`
`vi /etc/mysql/my.cnf`
增加以下内容
~~~
[mysqld]
server-id = 2
~~~
`server mysql restart`
~~~
mysql -uroot -p
mysql>change master to master_host='主服务器IP地址',master_port=3306,master_user='用户名',master_password='密码',master_log_file='master-bin.000001',master_log_pos=120;
mysql>start slave;
mysql>show slave status\G
~~~
成功:
![](https://box.kancloud.cn/2afe9a24c2fd796ab1afcc8520e45c8a_265x46.png)