多台 linux 主机的时间同步

当我们需要对多台 linux 主机进行时间同步的话,可以使用 ntp 工具实现

在所有主机上安装 ntp 工具

所有主机下执行

sudo apt-get install ntp

将一台主机作为时间服务器 (可选)

可使用一台主机作为时间服务器或者使用已有的第三方时间服务器

常用的国内第三方时间服务器

cn.pool.ntp.org  # 最常用的国内NTP服务器,参考:https://www.ntppool.org/zh/use.html
cn.ntp.org.cn    # 中国
edu.ntp.org.cn   # 中国教育网
ntp1.aliyun.com  # 阿里云
ntp2.aliyun.com  # 阿里云
ntp.sjtu.edu.cn  # 上海交通大学
s1a.time.edu.cn  # 北京邮电大学
s1b.time.edu.cn  # 清华大学
s1c.time.edu.cn  # 北京大学
s1d.time.edu.cn  # 东南大学
s1e.time.edu.cn  # 清华大学
s2a.time.edu.cn  # 清华大学
s2b.time.edu.cn  # 清华大学
s2c.time.edu.cn  # 北京邮电大学
s2d.time.edu.cn  # 西南地区网络中心
s2e.time.edu.cn  # 西北地区网络中心
s2f.time.edu.cn  # 东北地区网络中心
s2g.time.edu.cn  # 华东南地区网络中心
s2h.time.edu.cn  # 四川大学网络管理中心
s2j.time.edu.cn  # 大连理工大学网络中心
s2k.time.edu.cn  # CERNET桂林主节点

编辑配置文件,设置本机作为时间服务器:

# 默认配置文件位置为 /etc/ntp.conf 安装完 ntp 后会自动生成
vim /etc/ntp.conf

写入如下内容:

# 打开这个注释,代表允许 192.168 网段的服务器与此服务器进行时间同步
restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap
 
# 注释掉其他 server,添加如下 server,
# 127.127.1.0 表示本机地址,也可填写第三方时间服务器地址
server 127.127.1.0
 
# 这个配置的作用是告诉NTP,即使本地时钟源的层级是10,也可以使用它作为备用时钟源。通常情况下,本地时钟源的层级设置得比较高,以确保它不会被误认为是更精准的外部时钟源。
fudge 127.127.1.0 stratum 10

启动 ntp 服务

service ntpd start

设置为开机启动

chkconfig ntpd on

设置其他节点 ntp 同步时间服务器

编辑配置文件,设置一个时间服务器:

# 默认配置文件位置为 /etc/ntp.conf 安装完 ntp 后会自动生成
vim /etc/ntp.conf

写入如下内容:

# 注释掉其他 server,添加如下 server,<time server address> 填写时间服务器地址
server <time server address>

启动 ntp 服务

service ntpd start

设置为开机启动

chkconfig ntpd on

可以立即进行一次手动同步

ntpdate -d <time server address>

最后可以通过如下命令查看是否会定时同步

ntpq -p

Image

这里的 when 就代表上次同步距离现在的时间,通过这个时间久可以判断是否有在自动同步。