来自公众号:IT人家

NTP(Network Time Protocol,网络时间协议)是一种用于在网络中同步计算机系统时钟的协议,已有 40 多年的历史,被广泛应用于服务器、路由器、交换机和各种终端设备。
其主要功能是通过网络与标准时间源(如原子钟、GPS 或权威时间服务器)进行通信,使系统时间保持高度一致。
NTP 默认使用 UDP 123 端口进行通信,支持互联网和局域网内的时间同步,其时间精度在本地网络中通常可达到毫秒级,在互联网环境中也可达到数十毫秒级。
时间是一项非常关键的基础服务。在现代 IT 系统中,NTP 几乎是不可或缺的。
所有系统日志、应用日志、安全日志都依赖系统时间:
如果服务器时间不一致,将会导致日志顺序混乱、无法重现故障现场、审计追溯失效、安全取证困难等问题。在分布式系统中,多台服务器的时间偏差甚至可能造成严重误判
分布式系统依赖时间
现代 IT 架构大量采用分布式技术,例如:
如果节点间时间不同步,可能会导致数据写入冲突、选举失败(如 Raft / Zookeeper)、事务异常、心跳超时误判、Token/Session 失效等问题,严重时可能直接导致整个集群不可用
ntp.conf 示例(适用于 CentOS / RHEL / Rocky / Ubuntu 等):
# 漂移文件
driftfile /var/lib/ntp/drift
# 允许大时间漂移修正(首次启动)
tinker panic 0
# 默认拒绝所有访问,增强安全性
restrict default nomodify notrap nopeer noquery
# 允许本机
restrict 127.0.0.1
restrict ::1
# 局域网客户端允许访问(根据实际网段修改)
restrict 192.168.0.0 mask 255.255.255.0 nomodify notrap
# 上游时间服务器
server ntp1.aliyun.com iburst maxpoll 10 prefer
server ntp.sjtu.edu.cn iburst
server time.windows.com iburst
# 本地时钟作为兜底(防止断网失效)
server 127.127.1.0
fudge 127.127.1.0 stratum 10
# 关闭 ntpd 的客户端监控列表功能
disable monitor
# 指定监听网卡或者IP地址
interface listen eth0
interface listen 192.168.0.142
interface ignore wildcard
启动NTP服务
systemctl enable ntpd
systemctl start ntpd
查看NTP状态
# ntpq -pn
remote refid st t when poll reach delay offset jitter
==============================================================================
-118.31.40.99 100.100.61.91 2 u 997 1024 377 26.731 -1.520 2.157
+203.107.6.88 100.107.25.114 2 u 216 1024 377 40.192 2.637 1.899
*17.253.116.125 .MRS. 1 u 1 64 377 28.969 0.497 1.298
+20.189.79.72 10.0.6.24 3 u 42 1024 277 94.635 0.486 9.310
17.253.116.253 .MRS. 1 u 64 64 377 27.030 -0.103 0.065
注释:
查看选中时间源详细信息
ntpq -c rv
查看对等体
ntpq -c peers
查看同步状态
# ntpstat
synchronised to NTP server (17.253.116.125) at stratum 2
time correct to within 20 ms
polling server every 64 s
查看内核时间
ntptime
从指定 NTP 服务器获取时间,并立刻修改本机时间(一次性,不持续),如:
ntpdate ntp1.aliyun.com
常用参数:
-u 使用 UDP(穿越防火墙更好)
-b 强制立即修改时间
-q 只查询,不修改
· · · · · END · · · · ·