Linux 伺服器 NTP 校時相關指令紀錄

NTP 的設定及使用方式

目錄

紀錄一下有關 CentOS 中 NTP 的設定方式

安裝校時服務

1
sudo yum install ntp

設定 NTP BIOS 的時間也同步調整

1
2
sudo vi /etc/sysconfig/ntpd
#設定或加上 SYNC_HWCLOCK=yes

加入台灣的校時伺服器

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
sudo vi /etc/ntp.conf

server tick.stdtime.gov.tw prefer
server tock.stdtime.gov.tw prefer
server time.stdtime.gov.tw prefer
server clock.stdtime.gov.tw
server watch.stdtime.gov.tw
server time.windows.com
server tw.pool.ntp.org
server asia.pool.ntp.org
#server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4 #AWS主機可優先使用此校時伺服器
#server metadata.google.internal iburst #GCP 主機可優先使用此校時伺服器

開機自動啟動 ntp 校時服務

CentOS 6

1
sudo chkconfig ntpd on

CentOS 7

1
sudo systemctl enable ntpd

手動校時 & 寫入 BIOS

1
2
sudo ntpdate time.stdtime.gov.tw
sudo hwclock -w

查看目前系統時區

CentOS 6

1
ls -l /etc/localtime

CentOS 7

1
timedatectl

設定系統時區 (設定為台北)

CentOS 6

1
2
3
sudo cp /etc/localtime /root/old.timezone
sudo rm /etc/localtime
sudo ln -s /usr/share/zoneinfo/Asia/Taipei /etc/localtime

CentOS 7

1
sudo timedatectl set-timezone Asia/Taipei

設定防火牆

CentOS6

1
2
sudo iptables -A INPUT -m udp -p udp --sport 123 -d 0/0 --dport 123 -j ACCEPT
sudo iptables-save

CentOS7

1
2
sudo firewall-cmd --add-service=ntp --permanent
sudo firewall-cmd --reload

重新啟動校時伺服器

CentOS 6

1
sudo service ntpd restart

CentOS 7

1
sudo systemctl restart ntpd

確認是否成功 (需等待五分鐘在確認狀態)

1
ntpstat

確認目前與各個時間伺服器連線狀況

1
ntpq -p

remote - 本機和上層ntp的ip或主機名,“+”表示優先,“*”表示次優先
refid - 參考上一層ntp主機地址
st - stratum階層
when - 多少秒前曾經同步過時間
poll - 下次更新在多少秒後
reach - 已經向上層ntp服務器要求更新的次數
delay - 網絡延遲
offset - 時間補償
jitter - 系統時間與bios時間差

如果沒有使用 ntp 做校時, 則要手動排程校時,
crontab 設定範例如下

1
2
#校時
55 4 * * * root /usr/sbin/ntpdate server tick.stdtime.gov.tw && /sbin/hwclock -w

為什麼建議使用 ntpd 而不是 ntpdate

因為 ntpd 是平滑式的逐步調整時間,而 ntpdate 是斷點式的更新,
例如現在服務器時間是 9:18 分,而標準時間是 9:28 分,
ntpd 會在縮短內把時間校準到與標準時間相同,
而 ntpdate 會立即把時間調整到 9:28 分

如果你往資料庫內寫入內容或在其他對時間順序有嚴格要求的正式環境下,
產生的後果會是很嚴重的。

注意: 當本地時間與標準時間相差 30 分鐘以上時,ntpd 會停止工作

參考

linux服务之ntp与chrony  

如需轉載引用需保留原始連結及作者姓名,並以相同方式分享。CC BY-SA 4.0  

最後更新 2024/01/08 02:20 UTC
瀏覽次數
本站總訪問量
使用 Hugo 建立
主題 StackJimmy 設計