跳到主要内容

多台服务器使用 Rsync 同步代码

· 阅读需 4 分钟
大刘
一个 web 开发者

当多台服务器使用负载均衡等解决方案时,各服务器代码同步又是另一个问题,这时使用 Rsync 是一个常用的方案。这里以两台服务器为例

主服务器 A :192.168.0.2

辅服务器 B :192.168.0.3

安装配置 Rsync

安装 Rsync 并查看版本信息

yum install rsync
rsync -version

启动和停止 Rsync

/usr/bin/rsync --daemon --config=/etc/rsyncd.conf
ps -ef|grep rsync
kill 12521

配置主服务器 A, 首先简单配置下 Rsync,使用命令 vi /etc/rsyncd.conf

# 运行 Rsync 守护进程用户和组
uid = nobody
gid = nobody
# 允许最大连接数,就是预期多少台服务器链接
max connections = 4
# 只读模式
read only = true
# 预期链接的 IP,多个用逗号隔开
# hosts allow = 202.207.177.180
# 现在是允许所有的服务器都能连
hosts allow = *
transfer logging = true
log format = %h %o %f %l %b
# 日志文件
log file = /var/log/rsyncd.log
slp refresh = 300
# 进程文件位置
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsyncd.lock
[test]
# A 服务器需要同步的目录
path = /www/wwwroot/test
read only = false
# 允许的认证用户
auth users = root
# 密码文件位置
secrets file = /etc/rsyncd.password

接着设置上面配置文件中的密码文件 vim rsyncd.password 添加【user:password】格式的内容如:root:123456,并设置 600 权限,这点非常重要

chmod -R 600 rsyncd.password

配置辅服务器 B,这里只需要添加密码文件 vim rsyncd.password 添加【password】格式的内容如:123456

添加开机启动,防止服务器重启或者宕机修复好之后,需要手动重启服务

vi /etc/rc.local
/usr/bin/rsync --daemon --config=/ect/rsyncd.conf #开机自动运行

代码同步

配置好了 Rsync,现在就来实现服务器 B 从服务器 A 同步代码,执行以下命令

rsync -vzrtopg --progress root@192.168.0.2::test /www/wwwroot/test --password-file=/etc/rsyncd.password

root 对应服务器 A 配置文件 rsyncd.conf 中的 auth users = root

192.168.0.2 应服务器 A 的 IP

test 对应服务器 A 配置文件 rsyncd.conf 中的 [test]

/www/wwwroot/test 是服务器 B 存放同步代码的目录

/etc/rsyncd.password 是服务器 B 的密码文件

以上命令执行一次,同步一次,需要用到 crontab 计划任务来做到实时同步,新建 shell 脚本 vim /root/rsyncd.sh

#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
# 间隔的秒数,不能大于60
step=1
for (( i = 0; i < 60; i=(i+step) )); do
$(rsync -vzrtopg --progress root@192.168.0.2::test /www/wwwroot/test --password-file=/etc/rsyncd.password)
sleep $step
done
exit 0

然后在服务器 B 添加 crontab 定时任务,执行 crontab -e

* * * * * sh /root/rsyncd.sh > /dev/null 2>&1

OK,大功告成,赶紧去试试吧!

参考: https://blog.csdn.net/oljuydfcg/article/details/91639416