怎么同步CentOS系统时间
为什么需要同步系统时间
准确的系统时间对日志记录、定时任务、证书验证等场景至关重要。若服务器时间与标准时间偏差过大,可能导致服务异常或安全漏洞。
使用NTP服务自动同步时间
1. 安装NTP服务
# CentOS 7及以下版本
sudo yum install ntp
# CentOS 8及以上版本
sudo dnf install chrony
2. 配置NTP服务器
编辑配置文件(以chrony为例):
sudo vi /etc/chrony.conf
# 添加或替换NTP服务器地址
server ntp.aliyun.com iburst
server cn.pool.ntp.org iburst
3. 启动并启用服务
sudo systemctl enable chronyd
sudo systemctl start chronyd
# 检查服务状态
sudo systemctl status chronyd
手动同步时间命令
# 强制立即同步
sudo chronyc -a makestep
# 查看时间源状态
chronyc sources -v
验证时间同步状态
# 查看当前时间源
timedatectl
# 检查NTP同步状态
timedatectl | grep "NTP synchronized"
通过date命令临时调整时间
# 设置特定时间(格式:月日时分年.秒)
sudo date 031012302024.30
# 同步硬件时钟
sudo hwclock --systohc
防火墙配置(可选)
# 允许NTP服务端口
sudo firewall-cmd --add-service=ntp --permanent
sudo firewall-cmd --reload
常见问题解决
- 错误提示“No server suitable for synchronization”:检查网络连接或更换NTP服务器地址
- 时间同步后仍存在偏差:尝试重启chronyd服务:
sudo systemctl restart chronyd
- 硬件时钟不同步:执行
sudo hwclock --systohc
同步BIOS时间