正確的系統時區與精準的時間同步是日誌分析、定時任務、分布式事務、安全審計的基石。本文提供 CentOS/RHEL 7/8/9、Ubuntu 18.04+ 等主流發行版的時區設置、NTP/Chrony 時間同步、硬件時鐘寫入的標準化操作流程,並解釋底層機制。
/usr/share/zoneinfo/)。# 1. 列出所有时区
timedatectl list-timezones | grep Shanghai
# 2. 设置时区为中国标准时间 (CST, UTC+8)
timedatectl set-timezone Asia/Shanghai
# 3. 验证
timedatectl status
# 应显示:Time zone: Asia/Shanghai (CST, +0800)
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
# 1. 安裝 (通常預裝)
yum install -y chrony
# 2. 配置 NTP 服務器 (編輯 /etc/chrony.conf)
# 推薦使用阿里云/騰訊雲/教育網內部源,低延遲高穩定
server ntp.aliyun.com iburst
server ntp.tencent.com iburst
server cn.ntp.org.cn iburst
# 註釋掉預設的 pool.ntp.org
# 3. 啟用並啟動
systemctl enable --now chronyd
# 4. 強制立即同步 (首次/大偏差時)
chronyc makestep
# 5. 驗證同步狀態
chronyc sources -v
chronyc tracking
# 輸出應顯示 ^* 標記的源,System time 偏差 < 1ms
yum install -y ntp
# 編輯 /etc/ntp.conf 替換 server 行
systemctl enable --now ntpd
ntpdate -u ntp.aliyun.com # 立即同步 (ntpd 啟動前)
hwclock --systohc # 系統時寫入硬件時鐘 (UTC)
# 或 hwclock -w
timedatectl set-timezone Asia/Shanghai
timedatectl status
dpkg-reconfigure tzdata
# 界面選擇:Asia -> Shanghai
# 1. 編輯 /etc/systemd/timesyncd.conf
[Time]
NTP=ntp.aliyun.com ntp.tencent.com cn.ntp.org.cn
FallbackNTP=ntp.ubuntu.com
# 2. 啟用同步
timedatectl set-ntp true
# 等價於 systemctl enable --now systemd-timesyncd
# 3. 驗證
timedatectl timesync-status
# 或 timedatectl status 觀察 "System clock synchronized: yes"
apt install -y chrony
# 配置 /etc/chrony/chrony.conf (同 CentOS)
systemctl enable --now chrony
# 禁用 timesyncd 避免衝突
systemctl disable --now systemd-timesyncd
原則:硬件時鐘建議存儲 **UTC** 時間,由系統根據時區換算顯示本地時間。
# 查看當前 RTC 模式
timedatectl | grep "RTC in local TZ"
# 若為 yes (存儲本地時間),建議改為 UTC:
timedatectl set-local-rtc 0
# 將當前系統時間 (已同步、正確時區) 寫入硬件時鐘 (UTC)
hwclock --systohc
# 或 hwclock -w (舊命令,相同效果)
# 驗證
hwclock --show # 應顯示 UTC 時間
timedatectl # Local time 應為 CST (UTC+8),RTC time 為 UTC
避坑:雙系統 (Windows + Linux) 時,Windows 預設 RTC 存本地時間。Linux 可設 timedatectl set-local-rtc 1 --adjust-system-clock 兼容,但推薦修改 Windows 注冊表使其用 UTC。
# 1. 时区正确
timedatectl | grep "Time zone"
# Time zone: Asia/Shanghai (CST, +0800)
# 2. 时间同步生效
timedatectl | grep "synchronized"
# System clock synchronized: yes
# NTP service: active
# 3. RTC 为 UTC
timedatectl | grep "RTC in local TZ"
# RTC in local TZ: no
# 4. 硬件时间合理
hwclock --show
# 与 UTC 时间一致 (误差 < 1s)
-v /etc/localtime:/etc/localtime:ro -v /etc/timezone:/etc/timezone:ro。timedatectl set-timezone Asia/Shanghai。現代 Linux 時區/時間管理核心口訣:
用 timedatectl set-timezone Asia/Shanghai 定時區 → 用 chrony (或 timesyncd) 同時間 → 用 hwclock --systohc 寫硬件鐘 (UTC) → timedatectl status 全維驗證。