在Linux云服务器上配置自动时间同步可以确保系统时间准确,避免因时间偏差导致的服务异常(如证书验证、日志记录等问题)。以下是详细配置方案:
systemd-timesyncd
(适用于现代Linux发行版)大多数主流发行版(Ubuntu 16.04+/CentOS 8+/Debian 9+)已默认集成。
检查服务状态
timedatectl status
输出中若显示 NTP service: active
表示已启用。
启用NTP同步
sudo timedatectl set-ntp true
验证时间源
timedatectl show-timesync --all
ntpd
(传统NTP服务)适合需要更精细控制的场景。
安装ntpd
bash
sudo apt install ntp
bash
sudo yum install ntp
配置NTP服务器
编辑 /etc/ntp.conf
,替换为国内常用NTP池:
server ntp.aliyun.com iburst
server cn.pool.ntp.org iburst
启动并设置开机自启
sudo systemctl enable --now ntpd
验证同步状态
ntpq -p
chrony
(推荐用于动态环境)适合云服务器或频繁休眠/恢复的实例。
安装chrony
bash
sudo apt install chrony
bash
sudo yum install chrony
配置服务器
编辑 /etc/chrony.conf
,添加阿里云NTP:
server ntp.aliyun.com iburst
重启服务
sudo systemctl restart chronyd
sudo systemctl enable chronyd
检查同步状态
chronyc tracking
chronyc sources -v
手动强制同步
sudo ntpdate -u ntp.aliyun.com # ntpd/chrony需先停止服务
查看系统时间
date -R
防火墙放行NTP
sudo ufw allow 123/udp # Ubuntu
sudo firewall-cmd --add-service=ntp --permanent # CentOS
日志检查
journalctl -u systemd-timesyncd # systemd-timesyncd
tail /var/log/syslog # ntpd/chrony
chrony
(轻量、抗网络波动)ntpd
(稳定性高)systemd-timesyncd
(零配置)通过以上配置,服务器将自动保持时间同步,误差通常可控制在毫秒级。