跳转至

04 - 时间同步配置(systemd-timesyncd / chrony) ⏰

前提条件 ✅

  • 已完成 Debian 12 Bookworm 最小化安装 + apt 源优化
  • 系统能正常联网(可访问 pool.ntp.org 或国内 NTP 服务器)
  • 以 ops 用户登录(具有 sudo 权限)或 root
  • 虚拟机环境:VMware Workstation Pro(虚拟机时间同步已关闭,避免干扰)

重要提醒:VMware 默认会通过 VMware Tools 强制同步宿主机时间给虚拟机。
生产环境中强烈建议关闭 VMware 时间同步,让 Debian 自己管理时间。

详细步骤 🛠️

  1. 关闭 VMware Workstation Pro 的时间同步(防止冲突)
  2. 虚拟机 → 菜单 → VM → Settings → Options → VMware Tools
  3. 取消勾选 Synchronize guest time with host
  4. 或者在虚拟机 .vmx 文件中添加/确认以下行(关机状态下编辑):

    tools.syncTime = "FALSE"
    

  5. 检查当前时间状态

    timedatectl status
    timedatectl show-timesync
    date
    timedatectl list-timezones | grep Asia/Shanghai
    

  6. 方案一:使用 systemd-timesyncd(默认、轻量、推荐学习/中小型环境)

启用并配置(Debian 12 默认已安装):

sudo systemctl enable --now systemd-timesyncd

编辑配置文件(使用国内 NTP 服务器加速):

sudo systemctl edit systemd-timesyncd

输入以下内容(覆盖或追加):

[Time]
NTP=ntp.aliyun.com cn.pool.ntp.org time1.aliyun.com time2.aliyun.com
FallbackNTP=pool.ntp.org
RootDistanceMaxSec=5
PollIntervalMinSec=32
PollIntervalMaxSec=2048

重启服务并验证:

sudo systemctl restart systemd-timesyncd
timedatectl status               # 看 Time zone 和 NTP synchronized: yes
timedatectl timesync-status      # 查看同步详情
journalctl -u systemd-timesyncd -n 50

  1. 方案二:使用 chrony(推荐生产环境、大型集群、需要更高精度)

安装 chrony:

sudo apt update
sudo apt install -y chrony

备份并修改配置文件:

sudo cp /etc/chrony/chrony.conf /etc/chrony/chrony.conf.bak
sudo nano /etc/chrony/chrony.conf

推荐配置(替换 server 部分):

# 使用国内高精度 NTP 服务器
server ntp.aliyun.com iburst
server time1.aliyun.com iburst
server time2.aliyun.com iburst
server cn.pool.ntp.org iburst

# 允许本地子网客户端同步(视需求开启)
#allow 192.168.1.0/24

# 本地 stratum 10 作为备用
local stratum 10

重启并验证:

sudo systemctl restart chrony
sudo systemctl enable chrony
chronyc tracking
chronyc sources -v
chronyc sourcestats

  1. 设置时区(中国大陆统一使用 Asia/Shanghai)

    sudo dpkg-reconfigure tzdata
    # 依次选择:Asia → Shanghai
    
    # 或者命令行一步到位
    sudo timedatectl set-timezone Asia/Shanghai
    

  2. 最终验证

    date
    timedatectl
    chronyc tracking     # 如果用了 chrony
    

实践任务 🎯

  1. 关闭 VMware Tools 的时间同步功能
  2. 配置 systemd-timesyncd 使用阿里云 NTP 服务器并验证同步成功
  3. (可选进阶)安装 chrony,配置至少 3 个国内服务器,比较 chronyc tracking 输出
  4. 更改系统时区为 Asia/Shanghai 并确认 date 输出正确

自测问题 ❓

  1. 为什么生产环境中要关闭 VMware 的 guest 时间同步?
  2. systemd-timesyncdchrony 的主要适用场景区别是什么?
  3. 如何判断 NTP 同步是否正常工作(至少说出两种命令)?
  4. iburst 参数在 chrony/ntp 配置中的作用是什么?

总结 📌

时间同步是系统日志、证书验证、集群一致性等功能的基础。
Debian 12 默认的 systemd-timesyncd 足以满足大多数场景;生产级高可用环境推荐 chrony + 国内 NTP 池。
关闭虚拟化软件的时间同步干预是避免时间跳变的第一步。