服务器设置和教程 · 26 7 月, 2025

Ubuntu自動時間同步設定指南

在 Ubuntu 20.04 中設定時間同步非常簡單,因為系統預設使用 `systemd-timesyncd` 服務進行自動時間同步。以下是完整的設定步驟:

### 1. 檢查當前時間狀態
“`bash
timedatectl
“`
查看輸出中的關鍵資訊:
– `System clock synchronized`: 應為 `yes`(表示已啟用同步)
– `NTP service`: 應為 `active`(表示服務已啟用)

### 2. 啟用時間同步服務
“`bash
sudo timedatectl set-ntp on
“`

### 3. 重啟時間同步服務
“`bash
sudo systemctl restart systemd-timesyncd
“`

### 4. 驗證同步狀態
“`bash
timedatectl status
“`
確認:
– `System clock synchronized: yes`
– `NTP service: active`

### 5. (可選)設定自訂 NTP 伺服器
編輯設定檔:
“`bash
sudo nano /etc/systemd/timesyncd.conf
“`
修改內容(例如使用阿里雲 NTP 伺服器):
“`ini
[Time]
NTP=ntp.aliyun.com
FallbackNTP=ntp.ubuntu.com
“`
儲存後套用變更:
“`bash
sudo systemctl restart systemd-timesyncd
“`

### 6. (可選)設定時區
“`bash
# 列出所有時區
timedatectl list-timezones

# 設定時區(例如上海)
sudo timedatectl set-timezone Asia/Shanghai
“`

### 7. 查看詳細同步資訊
“`bash
systemctl status systemd-timesyncd
“`
輸出中應包含類似資訊:
“`
Active: active (running)
Status: “Synchronized to time server 203.107.6.88:123 (ntp.aliyun.com)”
“`

### 8. 手動強制同步(測試用)
“`bash
sudo systemctl stop systemd-timesyncd
sudo systemd-timesyncd –force
sudo systemctl start systemd-timesyncd
“`

### 常見問題解決:

**Q: 時間同步不工作怎麼辦?**
1. 檢查網路連線:
“`bash
ping ntp.aliyun.com
“`
2. 檢查防火牆是否允許 NTP(UDP 123端口):
“`bash
sudo ufw allow 123/udp
“`
3. 查看服務日誌:
“`bash
journalctl -u systemd-timesyncd
“`

**Q: 如何徹底停用時間同步?**
“`bash
sudo timedatectl set-ntp off
sudo systemctl stop systemd-timesyncd
sudo systemctl disable systemd-timesyncd
“`

> **注意**:
> – Ubuntu 20.04 預設使用 `systemd-timesyncd`,無需額外安裝軟體
> – 如果需要更高階的時間同步(如伺服器環境),可安裝 `chrony`:
> “`bash
> sudo apt install chrony
> sudo systemctl enable –now chrony
> “`
> – 硬體時鐘同步:`sudo hwclock –systohc`