Linux虚拟机如何配置NTP服务
导读:Linux虚拟机配置NTP服务 一 选择方案与准备 主流发行版的时间同步组件有两种:传统的 NTP(ntpd) 与较新的 chrony。一般而言,RHEL/CentOS 7 常用 ntpd,RHEL/CentOS 8+/Rocky Lin...
Linux虚拟机配置NTP服务
一 选择方案与准备
- 主流发行版的时间同步组件有两种:传统的 NTP(ntpd) 与较新的 chrony。一般而言,RHEL/CentOS 7 常用 ntpd,RHEL/CentOS 8+/Rocky Linux 8+ 默认使用 chrony。两者不要同时启用,避免端口与时钟步进策略冲突。
- 建议先统一时区并校准基础时间:
- 查看与设置时区:
timedatectl status、timedatectl set-timezone Asia/Shanghai - 校准一次硬件时钟:
hwclock -w(在系统时间正确后执行)
- 查看与设置时区:
- 虚拟机环境请确保网络连通与时间源可达(NTP使用 UDP 123 端口)。
二 方案一 使用 chrony(RHEL/CentOS 8+/Rocky 8+ 推荐)
- 安装与启用
- 安装:
yum install -y chrony(或dnf install -y chrony) - 启动并开机自启:
systemctl enable --now chronyd
- 安装:
- 服务端配置(作为局域网时间源)
- 编辑
/etc/chrony.conf:- 注释或删除默认
server行(若本机不向上级同步) - 允许客户端网段:
allow 192.168.1.0/24(按实际网段修改) - 定义本地时钟层级:
local stratum 10(上级不可达时作为备用源)
- 注释或删除默认
- 编辑
- 客户端配置(从服务器同步)
- 编辑
/etc/chrony.conf:将server指向服务器,例如:server 192.168.1.10 iburst
- 编辑
- 防火墙放行(若启用 firewalld)
firewall-cmd --add-service=ntp --permanent & & firewall-cmd --reload
- 验证
- 查看同步状态:
chronyc tracking、chronyc sources -v - 系统层面:
timedatectl(应看到 NTP enabled: yes、NTP synchronized: yes)
- 查看同步状态:
三 方案二 使用 NTP(ntpd,RHEL/CentOS 7 常见)
- 安装与启用
- 安装:
yum install -y ntp - 启动并开机自启:
systemctl enable --now ntpd
- 安装:
- 服务端配置
/etc/ntp.conf(示例)- 基本访问控制:
restrict default kod nomodify notrap nopeer noqueryrestrict -6 default kod nomodify notrap nopeer noqueryrestrict 127.0.0.1、restrict -6 ::1- 允许局域网:
restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap
- 上游时间源与本地时钟:
server 0.centos.pool.ntp.org iburstserver 1.centos.pool.ntp.org iburstserver 2.centos.pool.ntp.org iburstserver 3.centos.pool.ntp.org iburst- 本地时钟兜底:
server 127.127.1.0、fudge 127.127.1.0 stratum 10
- 基本访问控制:
- 客户端配置
/etc/ntp.conf- 指定服务器:
server 192.168.1.10 iburst
- 指定服务器:
- 防火墙放行
firewall-cmd --add-service=ntp --permanent & & firewall-cmd --reload
- 验证
- 端口:
ss -lunpt | grep 123(应看到 ntpd 监听 UDP 123) - 同步关系:
ntpq -p(关注*/+标记的同步源) - 系统状态:
timedatectl
- 端口:
四 常见问题与排障
- 防火墙/安全组未放行 UDP 123:在宿主机/网关放行对应端口,或临时测试可关闭防火墙验证。
- 虚拟机时间漂移严重:优先保证宿主机时间准确,启用虚拟化平台的 VM 时钟同步 辅助(与 NTP/chrony 配合,避免频繁大幅步进)。
- 同时使用 chrony 与 ntpd:二者会争用 123/323 端口,保留其一并禁用另一个。
- 上层不可达时:服务端配置本地时钟兜底(
local stratum 10或fudge 127.127.1.0 stratum 10),避免客户端失步。 - 权限限制过严:检查
restrict规则是否阻止了客户端访问(如缺少nomodify notrap的网段允许项)。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: Linux虚拟机如何配置NTP服务
本文地址: https://pptw.com/jishu/752756.html
