CentOS 7.x時間同步服務chrony配置詳解
作者:尹正傑
版權聲明:原創作品,謝絕轉載!否則將追究法律責任。
一.時間服務概述
1>.為什么需要時間服務器
事實上,我們各種電子設備它們都是靠時鍾驅動的,在分布式場景當中,更多主機的協作也是靠時鍾驅動的。因此,多節點的主機時間必須要一致。
以Linux為例,Linux的時間是系統啟動時,內核會從主板的硬件資源讀取時間並設置為內核中的時鍾。接下來系統時間和硬件的內核時間是各自分開獨立運行的。
由於操作系統在運行過程中CPU繁忙等各種原因,久而久之很可能會導致系統時鍾不精確的顯現,這種不精確反應在同一個集群的多台主機上其實就是集群時間不一致。
我們大家都知道虛擬機並獲得的CPU是虛擬機產品虛擬出來的CPU,並不是我們真正物理機上的CPU,因此出現時間誤差的概率是相當的大,所以在我們普遍使用雲計算的虛擬機上,必須要配置一個時間服務器,否則可能各個虛擬機的時間出現不一致的情況。
2>.ntpd時間服務
以RedHat的Linux發行版為例,早期用來解決時間服務器(CentOS 6.x版本之前)的程序包是ntpd,該程序包既可以用作服務端又可以用作客戶端。ntpd是基於NTP(Network Time Protocal)實現時間同步的。 ntdp的實現同步時間的邏輯: 它的思想是把時間的周期縮短,舉個例一個比較極限的例子,假設一台服務器兩台服務器時間相差1小時,它的思想就是將自己現有的時間周期縮短,從而間接追上時間服務器的時間。比如時間服務器跑一分鍾需要60秒,而ntpd的思想是跑一分鍾使用30秒甚至1秒實現跑一分鍾的的時間周期,這樣隨着時間的推移一定會追上服務器時間的。這種方式的確是可以追到服務器時間,但是為了追到服務器時間會付出一定時間的代價,這也是ntpd之所以被淘汰的根本原因。 生產環境中,你是否也發現了這樣的現象呢?明明在部署集群時時間配置是正確的,可能過了2三個月后,你會發現集群中總有那么幾台及其出現時間不同步的情況。這里的根本問題在於ntpd在和時間服務器進行時間同步的核心邏輯問題,因此CentOS7.x版本將CentOS6.x版本的ntpd替換為chronyd服務啦。 配置ntpd作為時間服務器案例(博主推薦使用使用chronyd作為服務端,盡管我之前也分效果使用ntpd作為服務端的比較): https://www.cnblogs.com/yinzhengjie/p/9480665.html
3>.chrony時間服務
chrony是網絡時間協議(NTP)的通用實現。它可以將系統時鍾與NTP服務器、參考時鍾(例如GPS接收器)和使用手表和鍵盤的手動輸入同步。它還可以作為NTPv4(RFC 5905)服務器和對等服務器運行,為網絡中的其他計算機提供時間服務。 它被設計成在各種條件下都能很好地運行,包括斷續的網絡連接、嚴重擁擠的網絡、不斷變化的溫度(普通的計算機時鍾對溫度很敏感),以及不連續運行或在虛擬機上運行的系統。 chrony是ntpd的替代方案。在互聯網上同步的兩台機器之間的典型精度在幾毫秒內;在局域網上,精度通常在幾十微秒內。使用硬件時間戳或硬件參考時鍾,可以達到亞微秒精度。 chrony中包含兩個程序,chronyd是一個可以在啟動時啟動的守護程序,chronyc是一個命令行接口程序,可用於監視chronyd的性能,並在運行時更改各種操作參數。 如果非要把NTP和chrony做一個對比的話,我們就以手動調整手表時間為例,我們假設手表時間和實際服務器時間相差3小時: ntpd的解決思路就是飛速的轉動秒針,以最快的速度調准時間,可想而是,我們需要非常快的速度轉動180圈秒針才能追上時間服務器的時間,真個轉動過程是相當費時間的。 chrony的解決思路就是直接調整時針,可想而知,我們挑撥時針不到一圈就能把問題解決掉了,這就是為什么生產環境中大家使用的時間服務器基本上都是chrony啦。 和ntpd一樣,chronyd程序包既可以做服務端也可以做客戶端,實際上chrony服務本身是兼容ntpd服務的,我們直到123/UDP是傳統的NTP服務所默認監聽的端口,而323/UDP是chrony所默認監聽的端口。因此我們使用chronyd做服務端后,我們既可以使用ntpd做客戶端也可以使用chronyd做客戶端。 chrony的官方網站: https://chrony.tuxfamily.org/
4>.chrony的優勢
chrony是網絡時間協議(NTP)的另一種實現,與網絡時間協議后台程序(ntpd)不同,它可以更快地且更准確地同步系統時鍾,請注意,ntpd仍然包含其中以供需要運行NTP服務的客戶使用。
chrony的優勢包括以下幾點:
(1)更快的同步只需要數分鍾而非數小時時間,從而最大程度減少時間和頻率誤差,這對於並非全天24小時的運行的台式計算機或系統而言非常有用;
(2)能夠更好地響應時鍾頻率的快速變化,這對於具備不穩定時鍾的虛擬機或導致賽事中頻率發生比變化的節能技術;
(3)在初始同步后,它不會停止時鍾,以防對需要系統時間保持單調的應用程序造成影響;
(4)在應對臨時非對稱延遲時(例如大規模下載造成鏈接飽和等情況)提供了更好的穩定性;
(5)無需對時間服務器進行定期輪詢,因此具備間歇性網絡連接(如網絡不穩定的場景)的系統仍然可以快速同步時鍾。
二.安裝並配置chrony服務
1>.安裝chrony

[root@master200.yinzhengjie.org.cn ~]# yum -y install chrony Loaded plugins: fastestmirror Determining fastest mirrors * base: mirror.bit.edu.cn * extras: mirror.bit.edu.cn * updates: mirrors.huaweicloud.com ambari-repo | 2.9 kB 00:00:00 base | 3.6 kB 00:00:00 extras | 2.9 kB 00:00:00 mysql-connectors-community | 2.5 kB 00:00:00 mysql-tools-community | 2.5 kB 00:00:00 mysql80-community | 2.5 kB 00:00:00 updates | 2.9 kB 00:00:00 (1/2): extras/7/x86_64/primary_db | 159 kB 00:00:00 (2/2): updates/7/x86_64/primary_db | 5.9 MB 00:00:00 Resolving Dependencies --> Running transaction check ---> Package chrony.x86_64 0:3.4-1.el7 will be installed --> Processing Dependency: libseccomp.so.2()(64bit) for package: chrony-3.4-1.el7.x86_64 --> Running transaction check ---> Package libseccomp.x86_64 0:2.3.1-3.el7 will be installed --> Finished Dependency Resolution Dependencies Resolved ============================================================================================================================================================================================================================================================================== Package Arch Version Repository Size ============================================================================================================================================================================================================================================================================== Installing: chrony x86_64 3.4-1.el7 base 251 k Installing for dependencies: libseccomp x86_64 2.3.1-3.el7 base 56 k Transaction Summary ============================================================================================================================================================================================================================================================================== Install 1 Package (+1 Dependent package) Total download size: 306 k Installed size: 788 k Downloading packages: (1/2): libseccomp-2.3.1-3.el7.x86_64.rpm | 56 kB 00:00:00 (2/2): chrony-3.4-1.el7.x86_64.rpm | 251 kB 00:00:00 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Total 957 kB/s | 306 kB 00:00:00 Running transaction check Running transaction test Transaction test succeeded Running transaction Installing : libseccomp-2.3.1-3.el7.x86_64 1/2 Installing : chrony-3.4-1.el7.x86_64 2/2 Verifying : libseccomp-2.3.1-3.el7.x86_64 1/2 Verifying : chrony-3.4-1.el7.x86_64 2/2 Installed: chrony.x86_64 0:3.4-1.el7 Dependency Installed: libseccomp.x86_64 0:2.3.1-3.el7 Complete! [root@master200.yinzhengjie.org.cn ~]#
2>.查看chrony是否已經安裝
[root@master200.yinzhengjie.org.cn ~]# yum info chrony Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile * base: mirrors.aliyun.com * extras: mirror.bit.edu.cn * updates: mirror.bit.edu.cn Installed Packages Name : chrony Arch : x86_64 Version : 3.4 Release : 1.el7 Size : 491 k Repo : installed #很顯然,這里已經提示咱們該程序包已經安裝成功啦~ From repo : base Summary : An NTP client/server URL : https://chrony.tuxfamily.org License : GPLv2 Description : A client/server for the Network Time Protocol, this program keeps your : computer's clock accurate. It was specially designed to support : systems with intermittent internet connections, but it also works well : in permanently connected environments. It can use also hardware reference : clocks, system real-time clock or manual input as time references. [root@master200.yinzhengjie.org.cn ~]#
3>.查看chrony服務安裝的文件
[root@master200.yinzhengjie.org.cn ~]# rpm -ql chrony /etc/NetworkManager/dispatcher.d/20-chrony /etc/chrony.conf #chrony的主配置文件 /etc/chrony.keys /etc/dhcp/dhclient.d/chrony.sh /etc/logrotate.d/chrony /etc/sysconfig/chronyd /usr/bin/chronyc #chronyc是一個命令行交互式接口程序,可用於監視chronyd的性能,並在運行時更改各種操作參數。 /usr/lib/systemd/ntp-units.d/50-chronyd.list /usr/lib/systemd/system/chrony-dnssrv@.service /usr/lib/systemd/system/chrony-dnssrv@.timer /usr/lib/systemd/system/chrony-wait.service /usr/lib/systemd/system/chronyd.service #CentOS 7.x版本對應的unit file /usr/libexec/chrony-helper /usr/sbin/chronyd #chronyd是一個可以在啟動時啟動的守護程序,它既可以充當服務端進程也可以充當服務端進程 /usr/share/doc/chrony-3.4 /usr/share/doc/chrony-3.4/COPYING /usr/share/doc/chrony-3.4/FAQ /usr/share/doc/chrony-3.4/NEWS /usr/share/doc/chrony-3.4/README /usr/share/man/man1/chronyc.1.gz /usr/share/man/man5/chrony.conf.5.gz /usr/share/man/man8/chronyd.8.gz /var/lib/chrony /var/lib/chrony/drift /var/lib/chrony/rtc /var/log/chrony [root@master200.yinzhengjie.org.cn ~]#
4>.查看chrony的幫助手冊
[root@master200.yinzhengjie.org.cn ~]# man chrony.conf #查看chrony的配置文件幫助信息 [root@master200.yinzhengjie.org.cn ~]# [root@master200.yinzhengjie.org.cn ~]# man chronyd #查看chrony的守護進程幫助信息
5>.服務端的配置文件(標記為粉紅色字體需要注意,其它使用默認參數即可,對其它字段感興趣的小伙伴可以參考上面的幫助信息喲)
[root@master200.yinzhengjie.org.cn ~]# cat /etc/chrony.conf #指定當前節點為服務器時間,生產環境中建議大家指定多個事件服務器喲,起到對時間服務器備份的效果 server master200.yinzhengjie.org.cn iburst # Record the rate at which the system clock gains/losses time. driftfile /var/lib/chrony/drift # Allow the system clock to be stepped in the first three updates # if its offset is larger than 1 second. makestep 1.0 3 # Enable kernel synchronization of the real-time clock (RTC). rtcsync # Enable hardware timestamping on all interfaces that support it. #hwtimestamp * # Increase the minimum number of selectable sources required to adjust # the system clock. #minsources 2 #指定允許的客戶端網段來當前時間服務器節點同步時間,我們可以使用deny all拒絕所有客戶端。 allow 172.200.0.0/21 #注意,如果主機位是0的話可以簡寫,比如下面的地址可以簡寫為"127/8",不過建議大家還是寫完整,可讀性更強。 allow 127.0.0.0/8 #如果上面使用server字段配置的時間服務器同步時間失敗,默認情況下當前時間服務器是不會向客戶端同步時間的, #這是因為擔心當前節點的時間不准確(因為當前節點沒有和定義中的server時間服務器進行同步),如果我們想要在 #server指定的時間服務器同步失敗的情況下依舊返回當前時間服務器的時間給客戶端,需要開啟該參數,這一項參 #數配置在生產環境中還是相當危險的,因此建議大家在server字段中指定互聯網的網絡時間,否則可能會出現整個 #集群時間都錯的的一致! local stratum 10 # Specify file containing keys for NTP authentication. #keyfile /etc/chrony.keys # Specify directory for log files. logdir /var/log/chrony # Select which information is logged. #log measurements statistics tracking [root@master200.yinzhengjie.org.cn ~]# [root@master200.yinzhengjie.org.cn ~]#
6>.客戶端配置(標記為粉紅色字體需要注意,其它使用默認參數即可,對其它字段感興趣的小伙伴可以參考上面的幫助信息喲)
[root@node201.yinzhengjie.org.cn ~]# egrep -v "^#|^$" /etc/chrony.conf server master200.yinzhengjie.org.cn iburst driftfile /var/lib/chrony/drift makestep 1.0 3 rtcsync logdir /var/log/chrony [root@node201.yinzhengjie.org.cn ~]#
7>.將chrony服務設置為開啟自啟動
[root@master200.yinzhengjie.org.cn ~]# systemctl start chronyd [root@master200.yinzhengjie.org.cn ~]# [root@master200.yinzhengjie.org.cn ~]# systemctl enable chronyd [root@master200.yinzhengjie.org.cn ~]# [root@master200.yinzhengjie.org.cn ~]# systemctl list-unit-files | grep chronyd chronyd.service enabled [root@master200.yinzhengjie.org.cn ~]# [root@master200.yinzhengjie.org.cn ~]# systemctl status chronyd ● chronyd.service - NTP client/server Loaded: loaded (/usr/lib/systemd/system/chronyd.service; enabled; vendor preset: enabled) Active: active (running) since Sun 2020-02-09 23:42:18 CST; 15h ago Docs: man:chronyd(8) man:chrony.conf(5) Main PID: 4678 (chronyd) CGroup: /system.slice/chronyd.service └─4678 /usr/sbin/chronyd Feb 09 23:42:17 master200.yinzhengjie.org.cn systemd[1]: Starting NTP client/server... Feb 09 23:42:18 master200.yinzhengjie.org.cn chronyd[4678]: chronyd version 3.4 starting (+CMDMON +NTP +REFCLOCK +RTC +PRIVDROP +SCFILTER +SIGND +ASYNCDNS +SECHASH +IPV6 +DEBUG) Feb 09 23:42:18 master200.yinzhengjie.org.cn chronyd[4678]: Frequency 0.298 +/- 0.488 ppm read from /var/lib/chrony/drift Feb 09 23:42:18 master200.yinzhengjie.org.cn systemd[1]: Started NTP client/server. Feb 09 23:42:28 master200.yinzhengjie.org.cn chronyd[4678]: Selected source 172.200.1.200 [root@master200.yinzhengjie.org.cn ~]# [root@master200.yinzhengjie.org.cn ~]#
8>.查看chrony服務的監聽端口

[root@master200.yinzhengjie.org.cn ~]# ss -untlp Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port udp UNCONN 0 0 *:123 *:* users:(("chronyd",pid=4678,fd=7))udp UNCONN 0 0 *:8472 *:* udp UNCONN 0 0 127.0.0.1:323 *:* users:(("chronyd",pid=4678,fd=5))udp UNCONN 0 0 ::1:323 :::* users:(("chronyd",pid=4678,fd=6))tcp LISTEN 0 20480 127.0.0.1:10248 *:* users:(("kubelet",pid=4659,fd=28))tcp LISTEN 0 20480 127.0.0.1:10249 *:* users:(("kube-proxy",pid=7373,fd=13))tcp LISTEN 0 20480 172.200.1.200:2379 *:* users:(("etcd",pid=6708,fd=6))tcp LISTEN 0 20480 127.0.0.1:2379 *:* users:(("etcd",pid=6708,fd=5))tcp LISTEN 0 20480 172.200.1.200:2380 *:* users:(("etcd",pid=6708,fd=3))tcp LISTEN 0 20480 127.0.0.1:2381 *:* users:(("etcd",pid=6708,fd=11))tcp LISTEN 0 20480 127.0.0.1:10257 *:* users:(("kube-controller",pid=6593,fd=6))tcp LISTEN 0 20480 127.0.0.1:10259 *:* users:(("kube-scheduler",pid=6659,fd=6))tcp LISTEN 0 128 *:22 *:* users:(("sshd",pid=5129,fd=3))tcp LISTEN 0 20480 127.0.0.1:17369 *:* users:(("kubelet",pid=4659,fd=9))tcp LISTEN 0 20480 :::10250 :::* users:(("kubelet",pid=4659,fd=23))tcp LISTEN 0 20480 :::30443 :::* users:(("kube-proxy",pid=7373,fd=10))tcp LISTEN 0 20480 :::10251 :::* users:(("kube-scheduler",pid=6659,fd=5))tcp LISTEN 0 20480 :::6443 :::* users:(("kube-apiserver",pid=6595,fd=5))tcp LISTEN 0 20480 :::10252 :::* users:(("kube-controller",pid=6593,fd=5))tcp LISTEN 0 20480 :::10256 :::* users:(("kube-proxy",pid=7373,fd=14))tcp LISTEN 0 128 :::22 :::* users:(("sshd",pid=5129,fd=4))tcp LISTEN 0 20480 :::30080 :::* users:(("kube-proxy",pid=7373,fd=8))[root@master200.yinzhengjie.org.cn ~]#
三.查看服務端和客戶端時間是否同步完成
1>.以交互式方式(支持命令補全)查看時間同步資源

[root@master200.yinzhengjie.org.cn ~]# [root@master200.yinzhengjie.org.cn ~]# chronyc chrony version 3.4 Copyright (C) 1997-2003, 2007, 2009-2018 Richard P. Curnow and others chrony comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions. See the GNU General Public License version 2 for details. chronyc> chronyc> sources 210 Number of sources = 1 MS Name/IP address Stratum Poll Reach LastRx Last sample =============================================================================== ^* master200.yinzhengjie.or> 10 10 377 15h -180ns[-2930ns] +/- 7588ns chronyc> chronyc>
2>.以交互式方式(支持命令補全)查看時間同步正常是否正常

[root@node201.yinzhengjie.org.cn ~]# chronyc chrony version 3.4 Copyright (C) 1997-2003, 2007, 2009-2018 Richard P. Curnow and others chrony comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions. See the GNU General Public License version 2 for details. chronyc> chronyc> sourcestats 210 Number of sources = 1 Name/IP Address NP NR Span Frequency Freq Skew Offset Std Dev ============================================================================== master200.yinzhengjie.or> 64 34 14h -0.000 0.001 -1ns 52us chronyc> chronyc>
3>.以非交互式方式(注意,不支持命令補全喲)查看時間同步資源詳細信息

[root@node201.yinzhengjie.org.cn ~]# chronyc sources -v 210 Number of sources = 1 .-- Source mode '^' = server, '=' = peer, '#' = local clock. / .- Source state '*' = current synced, '+' = combined , '-' = not combined, | / '?' = unreachable, 'x' = time may be in error, '~' = time too variable. || .- xxxx [ yyyy ] +/- zzzz || Reachability register (octal) -. | xxxx = adjusted offset, || Log2(Polling interval) --. | | yyyy = measured offset, || \ | | zzzz = estimated error. || | | \ MS Name/IP address Stratum Poll Reach LastRx Last sample =============================================================================== ^* master200.yinzhengjie.or> 11 10 377 8 +383ns[ +554ns] +/- 117ms [root@node201.yinzhengjie.org.cn ~]#
4>.通過chronyc交互式接口配置chrony訪問可參考幫助信息(不推薦使用,建議直接修改"/etc/chrony.conf"配置文件)

[root@master200.yinzhengjie.org.cn ~]# chronyc chrony version 3.4 Copyright (C) 1997-2003, 2007, 2009-2018 Richard P. Curnow and others chrony comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions. See the GNU General Public License version 2 for details. chronyc> help System clock: tracking Display system time information makestep Correct clock by stepping immediately makestep <threshold> <updates> Configure automatic clock stepping maxupdateskew <skew> Modify maximum valid skew to update frequency waitsync [<max-tries> [<max-correction> [<max-skew> [<interval>]]]] Wait until synchronised in specified limits Time sources: sources [-v] Display information about current sources sourcestats [-v] Display statistics about collected measurements reselect Force reselecting synchronisation source reselectdist <dist> Modify reselection distance NTP sources: activity Check how many NTP sources are online/offline ntpdata [<address>] Display information about last valid measurement add server <address> [options] Add new NTP server add peer <address> [options] Add new NTP peer delete <address> Remove server or peer burst <n-good>/<n-max> [<mask>/<address>] Start rapid set of measurements maxdelay <address> <delay> Modify maximum valid sample delay maxdelayratio <address> <ratio> Modify maximum valid delay/minimum ratio maxdelaydevratio <address> <ratio> Modify maximum valid delay/deviation ratio minpoll <address> <poll> Modify minimum polling interval maxpoll <address> <poll> Modify maximum polling interval minstratum <address> <stratum> Modify minimum stratum offline [<mask>/<address>] Set sources in subnet to offline status online [<mask>/<address>] Set sources in subnet to online status onoffline Set all sources to online or offline status according to network configuration polltarget <address> <target> Modify poll target refresh Refresh IP addresses Manual time input: manual off|on|reset Disable/enable/reset settime command manual list Show previous settime entries manual delete <index> Delete previous settime entry settime <time> Set daemon time (e.g. Sep 25, 2015 16:30:05 or 16:30:05) NTP access: accheck <address> Check whether address is allowed clients Report on clients that have accessed the server serverstats Display statistics of the server allow [<subnet>] Allow access to subnet as a default allow all [<subnet>] Allow access to subnet and all children deny [<subnet>] Deny access to subnet as a default deny all [<subnet>] Deny access to subnet and all children local [options] Serve time even when not synchronised local off Don't serve time when not synchronised smoothtime reset|activate Reset/activate time smoothing smoothing Display current time smoothing state Monitoring access: cmdaccheck <address> Check whether address is allowed cmdallow [<subnet>] Allow access to subnet as a default cmdallow all [<subnet>] Allow access to subnet and all children cmddeny [<subnet>] Deny access to subnet as a default cmddeny all [<subnet>] Deny access to subnet and all children Real-time clock: rtcdata Print current RTC performance parameters trimrtc Correct RTC relative to system clock writertc Save RTC performance parameters to file Other daemon commands: cyclelogs Close and re-open log files dump Dump all measurements to save files rekey Re-read keys from key file shutdown Stop daemon Client commands: dns -n|+n Disable/enable resolving IP addresses to hostnames dns -4|-6|-46 Resolve hostnames only to IPv4/IPv6/both addresses timeout <milliseconds> Set initial response timeout retries <retries> Set maximum number of retries keygen [<id> [<type> [<bits>]]] Generate key for key file exit|quit Leave the program help Generate this help chronyc>