在CentOS 7中同步网络时间,最常用且稳定的方案是使用NTP服务自动同步,以下是详细可执行步骤:
1. 安装NTP服务
通过YUM包管理器直接安装NTP软件包:
sudo yum install ntp -y
2. 配置NTP时间服务器
编辑NTP核心配置文件,指定国内稳定的时间源:
sudo vi /etc/ntp.conf
找到所有默认的server开头行,全部注释掉,添加国内阿里云公共NTP服务器(国内访问延迟低、稳定性高):
server ntp1.aliyun.com iburst
server ntp2.aliyun.com iburst
server ntp3.aliyun.com iburst
如果需要额外配置日志和访问权限,可以增加以下内容:
logfile /var/log/ntp.log
restrict default kod nomodify notrap nopeer noquery
restrict 127.0.0.1 mask 255.255.255.0 nomodify
3. (可选)设置系统时区
如果需要同步为北京时间,先设置正确时区:
timedatectl set-timezone Asia/Shanghai
4. 启动并设置开机自启
CentOS7默认使用chronyd做时间同步,若使用NTP服务需要先关闭chronyd,再启动ntpd:
# 关闭并禁用chronyd
systemctl stop chronyd
systemctl disable chronyd
# 启动ntpd并设置开机自启
sudo systemctl start ntpd
sudo systemctl enable ntpd
5. 第一次手动同步时间(可选,加快同步速度)
安装完成后可手动执行一次同步,让时间立刻对齐:
ntpdate -u ntp1.aliyun.com
6. 验证同步状态
执行以下命令查看NTP服务是否同步成功:
sudo ntpstat
如果输出synchronized to NTP server则说明同步成功,也可以用date命令查看当前时间是否准确官网。
补充说明:两种同步方式区别
- **直接同步(ntpdate)**:直接修改系统时间,速度快但如果时间误差过大可能导致任务重复执行,一般仅用于初次同步
- **平滑同步(ntpd)**:逐步修正时间误差,不会出现时间跳变,更适合服务器长期稳定运行,推荐使用该方案