linux下NTP服务器实战(chrony软件)
记录linux下NTP服务器搭建及相关管理操作,使用chrony软件包安装部署。相比ntp服务,Chrony服务适用于更高精度、更高稳定性、自动化等场景。
1. 安装 chrony
在大多数Linux发行版上,chrony
可以通过包管理器直接安装。
-
CentOS/RHEL:
sudo yum install chrony # CentOS 7 及之前的版本 sudo dnf install chrony # CentOS 8 和 Fedora
-
Ubuntu/Debian:
sudo apt install chrony
chrony 守护进程的默认位置为 /usr/sbin/chronyd
。命令行工具将安装到 /usr/bin/chronyc
。
2. 配置chrony
chrony
的配置文件通常位于/etc/chrony.conf
。要将机器配置为NTP服务器,需进行如下修改:
编辑 /etc/chrony.conf
文件:
sudo vim /etc/chrony.conf
-
允许网络客户端访问:
找到并修改或添加以下配置,允许特定网段或所有网络客户端访问:allow 192.168.0.0/24 # 允许指定网段访问 allow all # 允许所有客户端访问
-
选择上游时间源:
可以设置NTP服务器来同步本地时间。以下是一些常用的NTP服务器:server 0.centos.pool.ntp.org iburst server 1.centos.pool.ntp.org iburst server 2.centos.pool.ntp.org iburst
-
设置NTP服务器为本地时间主机:
如果此NTP服务器在不与外界同步的情况下应保持提供时间服务,可以启用本地时间作为时间源:local stratum 10
这里设置的
stratum
值较高,以避免本地时间被优先用于其他时间服务器。
配置文件示例:
[root@ntp ~]# cat /etc/chrony.conf
# Use public servers from the pool.ntp.org project.
# Please consider joining the pool (http://www.pool.ntp.org/join.html).
server 10.210.10.220 iburst
# 指定了一个 NTP 服务器的地址(10.210.10.220)。iburst 选项使得当客户端第一次与服务器进行通信时,如果无法立即建立连接,客户端会发送一组加速的请求(通常为 4 个包),以加快与时间服务器的同步速度。
# Record the rate at which the system clock gains/losses time.
driftfile /var/lib/chrony/drift
# driftfile 参数指定了存储系统时钟漂移数据的文件。系统定期测量其内部时钟的漂移(增快或减慢的速率)并记录到该文件中,这可以帮助 chrony 更好地调整系统时钟。
# Allow the system clock to be stepped in the first three updates
# if its offset is larger than 1 second.
makestep 1.0 3
# 允许在前 3 次时间更新时,如果系统时钟的偏差超过 1 秒,chrony 可以直接调整系统时钟,而不是渐进调整。这在系统启动后可以快速纠正较大的时间偏差。
# Enable kernel synchronization of the real-time clock (RTC).
rtcsync
# 启用内核的 RTC(实时时钟)同步。当系统时钟与 NTP 服务器同步时,内核会自动同步硬件时钟(通常是 BIOS 中的时钟)与系统时钟,以确保即使系统关机,硬件时钟也能保持准确。
# Enable hardware timestamping on all interfaces that support it.
#hwtimestamp *
# 这一行被注释掉了。如果启用,将会在所有支持硬件时间戳的网络接口上启用硬件时间戳。硬件时间戳可以提高网络延迟的精确度,尤其是在处理非常精确的时间同步时。
# Increase the minimum number of selectable sources required to adjust
# the system clock.
#minsources 2
# 如果启用,将设置系统调整时钟时所需的最少可用时间源数目为 2。这有助于确保同步的时间更为可靠。
# Allow NTP client access from local network.
# allow 192.168.0.0/16 # 允许特定的网络范围(如 192.168.0.0/16)内的客户端访问本地 NTP 服务。
# 默认情况下,远程的 NTP 客户端是无法与该 chrony 服务器进行时间同步的。需要通过 allow 指令明确地允许特定的网络范围或 IP 地址进行时间同步。
allow all # 允许所有客户端同步时间。
# Serve time even if not synchronized to a time source.
#local stratum 10
# 如果启用,即使本机没有与外部时间源同步,也会向网络上的其他设备提供时间服务,并将本地服务器的 stratum 设置为 10(即优先级较低的时间源)。
# Specify file containing keys for NTP authentication.
#keyfile /etc/chrony.keys
# 如果启用,它会指定一个包含 NTP 身份验证密钥的文件。这用于在服务器和客户端之间进行身份验证,确保同步时间的安全性。
# Specify directory for log files.
logdir /var/log/chrony
# logdir 参数指定了 chrony