引言
在生产环境中,时间准确性至关重要。无论是应用日志、数据库事务还是分布式系统的协调,都依赖于统一的时间。如果服务器时间漂移,可能导致:
- 日志顺序错乱,难以排查问题
- 数据库事务冲突或报错
- 分布式系统节点间出现不一致
因此,配置 自动时间同步 是运维的基础工作之一。本文将详细介绍如何在 linux 服务器上使用 chrony 来实现高精度的时间同步。
一、为什么选择 chrony
chrony 是 ntp 的现代替代方案,具有以下优势:
- 启动快:能在系统启动后迅速校准时间
- 精度高:适合虚拟机和容器环境
- 稳定性强:能处理网络延迟和抖动
- 配置简单:支持多源冗余,自动选择最佳时间源
二、安装 chrony
在 centos/rhel 系统中:
sudo yum install chrony -y sudo systemctl enable chronyd --now
在 ubuntu/debian 系统中:
sudo apt install chrony -y sudo systemctl enable chrony --now
三、配置国内 ntp 源
编辑配置文件 /etc/chrony.conf,添加国内常用的公共 ntp 服务器:
# 国家授时中心 server ntp.ntsc.ac.cn iburst # 阿里云 server ntp.aliyun.com iburst server ntp1.aliyun.com iburst server ntp2.aliyun.com iburst # 腾讯云 server time1.cloud.tencent.com iburst server time2.cloud.tencent.com iburst # 教育网(可选) server s1b.time.edu.cn iburst server ntp.sjtu.edu.cn iburst # 保留默认配置作为备用 pool 2.centos.pool.ntp.org iburst driftfile /var/lib/chrony/drift makestep 1.0 3 rtcsync logdir /var/log/chrony
修改完成后,重启服务:
sudo systemctl restart chronyd
四、验证同步状态
查看系统时间状态:
timedatectl status
输出中应看到:
system clock synchronized: yes ntp service: active
查看 chrony 同步详情:
chronyc tracking
关键指标:
- system time:偏差应在毫秒或微秒级
- leap status:应为 normal
查看时间源:
chronyc sources -v
输出中 ^* 表示当前正在使用的最佳源,^+ 表示备用源。
五、同步硬件时钟 (rtc)
避免重启后时间漂移:
sudo hwclock --systohc
六、应用层时区统一
确保数据库和应用层时间一致:
mysql:
show variables like '%time_zone%'; set global time_zone = '+8:00';
php (php.ini):
date.timezone = asia/shanghai
七、最佳实践
- 配置 至少 3~5 个国内源,保证冗余。
- 保留一个国际源作为备用。
- 所有服务器统一时区
asia/shanghai。 - 定期巡检:
chronyc tracking timedatectl status
八、总结
通过以上配置,你的 linux 服务器就能实现 自动时间同步,误差维持在微秒到毫秒级别。这样不仅能保证日志和数据库的一致性,还能为分布式系统提供稳定的时间基准。
以上就是linux服务器配置chron实现同步时间的详细教程的详细内容,更多关于linux chron同步时间的资料请关注代码网其它相关文章!
发表评论