萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

CentOS 系統時間設定三大法:本地時間、UTC、NTP 同步完整指南

Linux 系統時間分為系統時間(核心維護)與硬體時間(RTC/CMOS),同步來源可為本地設定、UTC 世界時或 NTP 網路校時。本文詳細說明三種模式配置、常用指令、hwclock/chrony/ntpd 工具用法與最佳實務。

系統時間架構

三種時間模式

模式描述配置檔適用場景
本地時間RTC 存儲本地時間(含 DST)/etc/localtime單系統、雙啟動 Windows
UTCRTC 存儲 UTC,核心換算顯示本地/etc/sysconfig/clock標準 Linux 伺服器、虛擬機
NTP 同步向上層時間伺服器校準/etc/ntp.conf 或 /etc/chrony.conf生產叢集、分散式系統、合規要求

工具與指令對照

hwclock / clock(RTC 操作)

# hwclock --show                 # 顯示硬體時間
# hwclock --set --date "03/17/2024 13:26:00"  # 設定硬體時間
# hwclock --hctosys              # 硬體 → 系統
# hwclock --systohc              # 系統 → 硬體
# hwclock -w                     # 同 --systohc

timedatectl(systemd 統一介面,推薦)

# timedatectl status
# timedatectl set-time "2024-03-17 13:26:00"
# timedatectl set-timezone Asia/Taipei
# timedatectl set-local-rtc 0    # 0=UTC, 1=Local
# timedatectl set-ntp true       # 啟用 systemd-timesyncd/chronyd/ntpd

date(系統時間)

# date -s "2024-03-17 13:26:00"
# date -s "03/17/2024"

NTP/Chrony 配置

Chrony(現代預設,適合間歇連網)

# /etc/chrony.conf
server time.google.com iburst
server time.cloudflare.com iburst
pool ntp.aliyun.com iburst
driftfile /var/lib/chrony/drift
makestep 1.0 3
rtcsync

# systemctl enable --now chronyd
# chronyc sources -v
# chronyc tracking

NTPD(傳統,高精度需求)

# /etc/ntp.conf
restrict default kod nomodify notrap nopeer noquery
restrict -6 default kod nomodify notrap nopeer noquery
server 0.centos.pool.ntp.org iburst
server 1.centos.pool.ntp.org iburst
server 2.centos.pool.ntp.org iburst
server 3.centos.pool.ntp.org iburst
driftfile /var/lib/ntp/drift

# systemctl enable --now ntpd
# ntpq -p
# ntpdate -u pool.ntp.org   # 手動立即同步

常用組合指令(手動設定後同步硬體)

# date -s "2024-03-17 13:26:00"
# hwclock -w

虛擬機特殊考量

  • 啟用 rtcsync(chrony)或 sync_cmos_clock(ntp),定期將系統時間寫回虛擬 RTC。
  • 避免在宿主機與客體同時運行 NTP 服務,由宿主機統一同步,客體透過 vmtoolsd / qemu-ga 同步。

驗證與除錯

# date; hwclock --show; timedatectl status
# journalctl -u chronyd -f
# ntpdate -q pool.ntp.org   # 僅查詢不設定

統一時間來源、正確配置時區與 RTC 模式,是分散式系統日誌對齊、資料庫一致性、安全審計的基石。

copyright © 萬盛學電腦網 all rights reserved