Linux Chrony 时间同步
时间在 Linux 服务器中扮演着重要角色,特别是在银行、股票市场和其他金融领域。如果我们希望所有 Linux 服务器都拥有正确的时间,那么必须配置一个 NTP 客户端,它将始终从远程 NTP 服务器获取正确的时间,并在需要时进行必要的调整以同步时间。
本文介绍如何在 Linux 服务器上使用 Chrony(NTP 客户端)与 NTP 服务器同步时间。
什么是 Chrony
Chrony 是一个网络时间协议(NTP)的实现,用于同步系统时钟。与传统的 ntp 相比,Chrony 能够更快、更准确地同步系统时钟。从 RHEL 8/CentOS 8 开始,ntp 不再可用,已被 chrony 取代。
Chrony 的主要特点:
- 更快的同步速度
- 更高的时间精度
- 更好的网络条件适应能力
- 支持离线模式(即使断开网络也能继续工作)
- 更安全的认证机制
安装 Chrony
Debian/Ubuntu 系统
sudo apt update
sudo apt install -y chrony
RedHat/CentOS 系统
对于 CentOS 7 及更早版本:
sudo yum install -y chrony
对于 CentOS 8/RHEL 8 及更新版本:
sudo dnf install -y chrony
Fedora 系统
sudo dnf install -y chrony
验证安装
安装完成后,Linux 系统会增加两个命令:
验证安装:
# 检查 chronyc 命令
chronyc --version
# 检查 chronyd 服务
systemctl status chronyd
配置 Chrony
Chrony 的配置文件在不同发行版上的位置略有不同,通常是 /etc/chrony.conf 或者 /etc/chrony/chrony.conf。
配置文件位置
# 查找配置文件位置
ls -l /etc/chrony.conf /etc/chrony/chrony.conf 2>/dev/null
# 或使用命令查找
chronyd -V | grep "config file"
配置文件示例
以下是 Ubuntu 系统的默认配置文件示例:
/etc/chrony/chrony.conf
# Welcome to the chrony configuration file. See chrony.conf(5) for more
# information about usuable directives.
# This will use (up to):
# - 4 sources from ntp.ubuntu.com which some are ipv6 enabled
# - 2 sources from 2.ubuntu.pool.ntp.org which is ipv6 enabled as well
# - 1 source from [01].ubuntu.pool.ntp.org each (ipv4 only atm)
# This means by default, up to 6 dual-stack and up to 2 additional IPv4-only
# sources will be used.
# At the same time it retains some protection against one of the entries being
# down (compare to just using one of the lines). See (LP: #1754358) for the
# discussion.
#
# About using servers from the NTP Pool Project in general see (LP: #104525).
# Approved by Ubuntu Technical Board on 2011-02-08.
# See http://www.pool.ntp.org/join.html for more information.
pool ntp.ubuntu.com iburst maxsources 4
pool 0.ubuntu.pool.ntp.org iburst maxsources 1
pool 1.ubuntu.pool.ntp.org iburst maxsources 1
pool 2.ubuntu.pool.ntp.org iburst maxsources 2
# This directive specify the location of the file containing ID/key pairs for
# NTP authentication.
keyfile /etc/chrony/chrony.keys
# This directive specify the file into which chronyd will store the rate
# information.
driftfile /var/lib/chrony/chrony.drift
# Uncomment the following line to turn logging on.
#log tracking measurements statistics
# Log files location.
logdir /var/log/chrony
# Stop bad estimates upsetting machine clock.
maxupdateskew 100.0
# This directive enables kernel synchronisation (every 11 minutes) of the
# real-time clock. Note that it can't be used along with the 'rtcfile' directive.
rtcsync
# Step the system clock instead of slewing it if the adjustment is larger than
# one second, but only in the first three clock updates.
makestep 1 3