ntp是自动时间同步,需要至少有一台主ntp服务器(同步时钟)和一台从ntp客户端(对标同步时钟调整的主机),当然服务器和客户端可以部署在同一台物理机上,这里只是在软件层面上进行区分。
ntp的服务进程为ntpd,下载方式可以使用 yum -y install ntp
进行安装,默认配置文件会存放在/etc/ntp.conf。
服务端配置:
#注释以下4行
#server 0.centos.pool.ntp.org iburst
#server 1.centos.pool.ntp.org iburst
#server 2.centos.pool.ntp.org iburst
#server 3.centos.pool.ntp.org iburst
#新增以下两行
server 127.127.1.0 prefer
#127.127.1.0表示本地时钟,prefer表明此主机ip为优先ip,即优先同步该主机的时间,如果注释掉了以上4行,可不用填写
fudge 127.127.1.0 stratum 10
#这里的stratum表示ntp服务器层级,如果为0则表示层级最高,不向其他任何ntp服务器获取同步时间
客户端配置:
#注释以下4行
#server 0.centos.pool.ntp.org iburst
#server 1.centos.pool.ntp.org iburst
#server 2.centos.pool.ntp.org iburst
#server 3.centos.pool.ntp.org iburst
server ntp主服务器ip
至此就完成了简单的ntp服务端和客户端的配置,非常简单,但在开启ntp客户端之前建议先使用 ntpdate ntp主服务器ip
来手动进行时间同步,此过程需要先保证ntp主服务器已开启。原因是ntp自动同步采用时间校准的方式,虽然同步时间慢但是可靠,在同步过程中,如果ntp服务器和客户端的时间差太大(约1000秒),则不会进行自动同步。因此,保险起见,建议先在启动ntp服务前进行手动同步时间。
接着使用 systemctl start ntpd
和 systemctl enable ntpd
开启和开机自启动ntp服务开始ntp时间同步。可以在客户端使用ntpstat
来检验时间是否正在同步(同步启动需约5分钟)。
另外,值得一提的是,不建议直接采用 ntpdate+crontab 的方式进行时间同步,因为强行进行时间跳跃很容易导致诸如“sleep”等依赖时间的进程受到影响。其次是ntpdate默认只同步“软时间”,要想同时同步“硬时间”可将配置文件/etc/sysconfig/ntpdate中的SYNC_HWCLOCK=no改为SYNC_HWCLOCK=yes。
以下是ntp服务的搭建步骤:
服务端:
1、安装ntp服务
yum install -y ntp
2、修改ntp配置文件
server 127.127.1.0
fudge 127.127.1.0 stratum 10
3、启动和开机自启动ntp服务
systemctl start ntpd
systemctl enable ntpd
4、查看配置是否成功
ntpq -p(显示LOCAL即成功)
客户端:
1、安装ntp服务
yum install -y ntp
2、修改ntp配置文件
server ntp主服务器ip
3、开启前手动同步时间,避免因时差大导致无法正常自动同步
ntpdate ntp主服务器ip
4、启动和开机自启动ntp服务
systemctl start ntpd
systemctl enable ntpd
5、查看ntp是否正在同步
ntpstat(以下截图表示成功,如出现unsynchronised则等待几分钟即可)