使用ntp可以将节点和服务器之间的时间同步。同步的是系统时间(即date命令查看)。详细介绍参考http://doc.ntp.org/4.1.0/ntpd.htm
配置了ntp server后,client端才能和server端同步
配置文件路径是/etc/ntp.conf
在其中添加
server ntp.ntsc.ac.cn prefer
server 127.0.0.1
可以添加多个server,这样在其中一个server不能联通时会去跟别的server同步。加上prefer表示首先以该server为标准同步
可以用于同步的server可以参考下面的连接
https://dns.icoa.cn/ntp/
在添加server前,先检查client到server是否联通
ntpdate -d ntp.ntsc.ac.cn
如果显示有下面的结果表示可以用这个ip作为ntp server。其中最后一行信息表示client和server目前相差多少时间,如截图现在是clinet慢130s
配置文件完成保存后,重启ntp服务,即会开始同步。同步不是立刻进行的,会有一定的时间周期来检查是否存在时间差
systemctl restart ntp
可以用下述命令来检查client与server的同步情况。这些命令都不是实时的,需要一段时间才会刷新。
1.
ntpq -p
ntpstat
通过设置ntp server + 重启ntp服务的方式,可以让client快速的与server端同步。但是有的时候我们并不希望时间出现大跨度的变化,尤其是一个集群需要时间同步的时候。ntp提供了可以逐步调整时间的方法,以ms为跨度逐渐调整client时间到server的当前时间。
根据官网的介绍,ntpd可以携带不同的参数。其中的-x参数就提供了逐步逼近时间的功能。但是其中有个限制:超过1000s,ntpd不能进行设置。可以加入-g参数调整
-x
Normally, the time is slewed if the offset is less than the step threshold, which is 128 ms by default, and stepped if above the threshold. This option forces the time to be slewed in all cases. If the step threshold is set to zero, all offsets are stepped, regardless of value and regardless of the -x option. In general, this is not a good idea, as it bypasses the clock state machine which is designed to cope with large time and frequency errors Note: Since the slew rate is limited to 0.5 ms/s, each second of adjustment requires an amortization interval of 2000 s. Thus, an adjustment of many seconds can take hours or days to amortize. This option can be used with the -q option.
-g
Normally, ntpd exits if the offset exceeds the sanity limit, which is 1000 s by default. If the sanity limit is set to zero, no sanity checking is performed and any offset is acceptable. This option overrides the limit and allows the time to be set to any value without restriction; however, this can happen only once. After that, ntpd will exit if the limit is exceeded. This option can be used with the -q option.
具体方法:
修改/etc/sysconfig/ntpd文件,其中的OPTIONS可以增加参数,修改后重启ntpd服务即可生效
# Command line options for ntpd
OPTIONS="-x -g -p /var/run/ntpd.pid"
SYNC_HWCLOCK=yes
先停止ntpd服务再手动执行命令也可生效
ntpd -x -g