在Linux系统中配置NTP(Network Time Protocol)服务器是确保系统时间准确同步的重要任务,尤其对于需要高精度时间同步的服务(如数据库、分布式系统、日志服务器等)而言至关重要,以下是详细的Linux NTP服务器配置步骤,包括环境准备、安装配置、防火墙设置及客户端同步等内容。

环境准备与安装
确保服务器操作系统为稳定版本(如CentOS 7/8、Ubuntu 18.04/20.04等),并以root权限或具有sudo权限的用户登录,NTP服务通常通过ntpd或chrony包提供,其中chrony在高动态网络环境中性能更优,推荐优先使用,以CentOS 7为例,执行以下命令安装chrony:
yum install chrony -y
对于Ubuntu系统,使用:
apt update && apt install chrony -y
配置NTP服务器
安装完成后,编辑NTP配置文件。chrony的配置文件为/etc/chrony.conf,ntpd的配置文件为/etc/ntp.conf,以chrony为例,打开配置文件:
vi /etc/chrony.conf
核心配置参数包括:

-
服务器源:指定上游NTP服务器,可选择公共服务器(如pool.ntp.org)或内部时间服务器,推荐使用以下配置:
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
iburst参数表示在初始同步时快速发送请求,缩短同步时间。 -
本地时钟同步:允许其他客户端从本服务器同步时间,添加:
allow 192.168.1.0/24 # 允许192.168.1.0网段的主机同步 local stratum 10 # 将本地时钟设为stratum 10,优先使用上游服务器
-
其他优化参数:
(图片来源网络,侵删)driftfile /var/lib/chrony/driftfile # 记录时钟频率偏差 makestep 1.0 3 # 如果时间偏差超过1秒,允许3步内调整
配置完成后保存文件,并启动chrony服务:
systemctl enable chronyd systemctl start chronyd systemctl status chronyd # 确认服务运行正常
防火墙与SELinux设置
若服务器启用了防火墙(如firewalld),需开放NTP服务的UDP 123端口:
firewall-cmd --permanent --add-service=ntp firewall-cmd --reload
对于SELinux,确保其策略允许NTP服务:
setsebool -P ntpd_can_network_connect 1
验证NTP服务器状态
使用chronyc命令监控同步状态:
chronyc sources -v # 查看上游服务器同步状态 chronyc tracking # 查看时钟同步信息
若显示标记的源,表示已成功同步,客户端可通过ntpdate或chronyc测试同步:
chronyc -a 192.168.1.100 # 替换为NTP服务器IP
客户端配置
客户端安装chrony后,修改/etc/chrony.conf,将服务器指向NTP服务器IP:
server 192.168.1.100 iburst
重启服务后,客户端即可与服务器同步时间。
常见问题排查
- 同步失败:检查防火墙、SELinux设置,确认服务器时间与上游服务器差距过大时,手动同步:
chronyc makestep
- 高延迟:调整
chrony.conf中的maxdistance参数,或更换上游服务器。
相关问答FAQs
Q1: 如何确认NTP服务器是否正常工作?
A1: 可通过以下命令验证:
chronyc sources -v:查看是否有标记的活跃服务器源。ntpq -p(若使用ntpd):检查reach列是否为非零值,delay和offset值是否在合理范围内(通常offset应小于100ms)。timedatectl status:确认系统时间是否为“使用NTP同步”。
Q2: 客户端无法同步时间,可能的原因有哪些?
A2: 常见原因包括:
- 网络问题:客户端与服务器间防火墙未开放UDP 123端口,或网络不通。
- 配置错误:客户端
chrony.conf或ntp.conf中的服务器IP错误,或服务器未配置允许客户端同步(如未添加allow指令)。 - 时间偏差过大:若服务器与客户端时间差超过1000秒,需手动同步(
chronyc makestep或ntpdate -s server_ip)。 - 服务未启动:检查服务器和客户端的
chronyd或ntpd服务状态。
