1. NTP服务简介

NTP(Network Time Protocol,网络时间协议)是用来使网络中的各个计算机时间同步的一种协议。它的用途是把计算机的时钟同步到世界协调时UTC,其精度在局域网内可达0.1ms,在互联网上绝大多数的地方其精度可以达到1-50ms。
NTP服务器就是利用NTP协议提供时间同步服务的。

2. NTP服务搭建

2.1. 环境准备

使用VMware虚拟化安装linux系统并将网络环境设置为NAT,可以连上外网

主机名称IP地址系统版本角色
linux-node1192.168.66.11CentOS 7NTP服务器
linux-node2192.168.66.12CentOS 7客户端

注意:关闭系统selinux和防火墙

2.2. 安装NTP服务

查看系统是否安装 ntp服务

~]# rpm -qa ntp
ntp-4.2.6p5-28.el7.centos.x86_64

若没有安装可以使用 YUM 命令进行安装即可

~]# yum -y install ntp

2.3. 配置NTP服务

ntp 服务器默认是不运行客户端进行时间同步的,所有我们需要配置文件设置允许。NTP服务的默认配置文件是/etc/ntp.conf

~]# cp /etc/ntp.conf{,_$(date +%Y%m%d%H)}
~]# vim /etc/ntp.conf   
………省略内容………
#restrict default kod nomodify notrap nopeer noquery    注释此行内容 
# nomodify 客户端不可以修改时间参数但是可以同步时间服务器,添加以下内容 
restrict default nomodify   
以下为 NTP服务默认的时间同步源,先将其注释 
#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 time1.aliyun.com
………省略内容………

2.4. 启动NTP服务

客户端先将系统优化是定时任务自动同步时间服务器的定时任务注释,如果不注释的话可能会
冲突
提示:本地的 ntp 时间服务器会跟互联网的时间服务器冲突,只能选择一个进行同步。

~]# crontab -l
# time sync by albert at 2019-02-10
#*/5 * * * * /usr/sbin/ntpdate time1.aliyun.com &>/dev/null
~]# systemctl enable ntpd.service 
Created symlink from /etc/systemd/system/multi-user.target.wants/ntpd.service to /usr/lib/systemd/system/ntpd.service.
~]# systemctl start ntpd.service
# 查看ntp服务器的详细状态
~]# ntpq -p
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
 203.107.6.88    10.165.84.13     2 u   28   64    1   15.767  708.472   0.000
# 显示网络时间同步状态 
# 使用ntpstat 命令查看时间同步状态,这个一般需要5-10分钟后才能成功连接和同步。所以,服务器启动后需要稍等下.
# 刚启动的时候,一般是:
~]# ntpstat
unsynchronised
  time server re-starting
   polling server every 8 s
# 连接并同步后:

3. 客户机时间同步

客户机要等几分钟再与新启动的 ntp 服务器进行时间同步,否则会提示 no server suitable for synchronization found 错误。

~]# ntpdate 192.168.66.11
14 Feb 11:27:59 ntpdate[6528]: no server suitable for synchronization found

客户端同步时间的方法:

~]# ntpdate 192.168.66.11
  14 Feb 11:37:25 ntpdate[1453]: step time server 192.168.66.11 offset 0.880807 sec
# 将命令放入计划任务即可
~]# crontab -l
*/5 * * * * /usr/sbin/ntpdate 192.168.66.11 &>/dev/null

4. 注意事项

当我们搭建 NTP 服务器的时候一定要先将后面优化的时间同步定时任务注释,不然会产生冲突

常见错误 1:No association ID's returned

检查网络是否连通:ping www.baidu.com

常见错误 2:

~]# ntpdate 192.168.66.11
Error resolving 192.168.66.11: Servname not supported for ai_socktype (-8) 
 14 Feb 11:37:25 ntpdate[1411]: Can't find host 192.168.66.11: Servname not supported for ai_socktype (-8) 
 14 Feb 11:37:25 ntpdate[1411]: no servers can be used, exiting

客户机要等几分钟再与新启动的 ntp 服务器进行时间同步,否则会提示 no server suitable for synchronization found 错误。

可能原因:客户端缺少什么配置文件

检查客户端是否可以与互联网的时间服务器同步,若不行,就是客户端的问题!排查客户端故障

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐