✅ 推荐方案:使用 chrony
搭建 NTP 服务器(适用于 CentOS 7/8/9)
chrony
是 CentOS 推荐的 NTP 实现,精度高、资源占用低、同步快,默认在 CentOS 8+ 中取代了 ntpd
。
🔧 一、安装 chrony
sudo yum install -y chrony
📁 二、修改配置 /etc/chrony.conf
sudo vi /etc/chrony.conf
找到并修改或添加以下内容:
1. 配置上游 NTP 服务器(可用公网 NTP)
例如:
server ntp.aliyun.com iburst server ntp.tencent.com iburst
2. 允许内网客户端访问本 NTP 服务器:
(假设客户端在 192.168.1.0/24
网段)
allow 192.168.1.0/24
也可以使用 allow 0.0.0.0/0
表示允许所有地址访问(不安全,慎用)
🔃 三、启动并设置开机自启
sudo systemctl enable chronyd sudo systemctl start chronyd
🔥 四、放通防火墙 UDP 123 端口
sudo firewall-cmd --add-service=ntp --permanent sudo firewall-cmd --reload
如果你没有使用 firewalld
,用 iptables
:
sudo iptables -A INPUT -p udp --dport 123 -j ACCEPT sudo service iptables save
🔍 五、验证本地是否在同步
chronyc tracking chronyc sources -v
查看是否监听 123 端口:
sudo netstat -unlp | grep 123
应看到 chronyd
正在监听 UDP 123。
🧪 六、客户端如何使用你的服务器同步时间?
1. 确保 systemd-timesyncd
已安装并启用
Ubuntu / Debian
sudo systemctl enable systemd-timesyncd
sudo systemctl start systemd-timesyncd
CentOS(默认无 timesyncd
,建议改用 chrony
)
2. 编辑 timesyncd
配置
sudo vi /etc/systemd/timesyncd.conf
修改或添加:
[Time] NTP=你的服务器IP或域名
示例:
[Time] NTP=192.168.1.100
然后重启服务:
sudo systemctl restart systemd-timesyncd
启用 NTP 自动同步:
sudo timedatectl set-ntp true
3. 验证是否同步成功
timedatectl status
应看到:
NTP service: active System clock synchronized: yes
还可以查看详细信息:
timedatectl show-timesync --all
📌 七、补充说明:使用 ntpd(旧方法,不推荐)
若你坚持使用传统 ntpd
:
sudo yum install ntp
sudo vi /etc/ntp.conf
修改:
server ntp.aliyun.com iburst
restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap
然后启动服务并开启端口:
sudo systemctl enable ntpd
sudo systemctl start ntpd
✅ 总结:搭建 NTP 服务器步骤(Chrony版)
步骤 | 命令或说明 |
---|---|
安装服务 | yum install chrony |
编辑配置 | /etc/chrony.conf ,配置上游时间源 + allow 网段 |
启动服务 | systemctl start chronyd |
开机自启 | systemctl enable chronyd |
放通防火墙 | firewall-cmd --add-service=ntp --permanent |
客户端连接 | server <服务器IP> iburst |