时间同步
在配置集群等服务时,需要保持多台主机的时间统一。
本文不涉及配置 NTP 服务器对外服务,而是如何配置 NTP 客户端。
对于简单的时间同步, systemd 自带的 NTP 客户端就足以满足要求,但如果有多一点的需求 ( 例如你需要连接一个硬件来提供时钟 ) ,则需要安装 ntpd 服务。
systemd-timesyncd
当系统安装后,只要安装时网络畅通,则 Debian 会自动配置 systemd-timesyncd 并与 Debian 的官方时间服务器同步。
要增加 NTP 服务器,则需要修改 /etc/systemd/timesyncd.conf
# This file is part of systemd.
#
# systemd is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Entries in this file show the compile time defaults.
# You can change settings by editing this file.
# Defaults can be restored by simply deleting this file.
#
# See timesyncd.conf(5) for details.
[Time]
#NTP=
#FallbackNTP=0.debian.pool.ntp.org 1.debian.pool.ntp.org 2.debian.pool.ntp.org 3.debian.pool.ntp.org
#RootDistanceMaxSec=5
#PollIntervalMinSec=32
#PollIntervalMaxSec=2048添加服务器需要取消 NTP= 这一行的注释,并填入 NTP 服务器地址。
例如:
多服务器间用空格分割。
保存更改后,重启 systemd-timesyncd 服务
之后验证配置
使用 timedatectl show-timesync --all
NTP 服务器选择顺序如下:
systemd-networkd.service(8)中针对每个接口的配置,或者 DHCP 服务优先。/etc/systemd/timesyncd.conf中定义的 NTP服务器会在运行时被添加到针对每个接口的服务器列表中,守护进程会轮流连接这些服务器直到某个有应答。如果上两步没有取到 NTP 服务器, 那么就是用
FallbackNTP=中定义的服务器。
要启用并运行:
同步需要一点时间,可能会卡住。
查看状态使用:
ntpd
如果需要更多的特性,或需要同时部署 NTP 服务器,则需要安装 ntpd 软件包。
ntpd 与 系统自带的 systemd-timesyncd 有冲突,需要停止自带服务。
作为客户端接收时间
systemd 自带的 timedatectl 只能控制系统自带的 systemd-timesyncd,使用 timedatectl set-ntp true 会停止 ntpd 服务。
安装 ntpd 服务
修改配置文件 /etc/ntp.conf
在 23 行处可修改原始服务器地址为所需的服务器地址:
例如修改为:
重启服务生效:
使用 ntpq -p 查看同步状态
delay, offset 和 jitter 不应该为零,ntpd 同步的服务器前有星号,ntpd 可能等待几分钟后才会进行同步
作为服务器下发时间
对 ntpd 进行服务器配置需要对配置文件进行修改
在 33-55 行带有配置示例:
为确保失去网络也能提供同步服务,需要增加一个本地时间作为时间源:
接下来新增策略,允许局域网内的主机与本机同步时间,例如本例中我的局域网 IP 为 192.168.50.0/24,则可以写为
此处的 nomodify 意为不允许客户端使用 ntpq 或 ntpdc 修改服务器配置。
所有的选项可以通过 ntp.conf(5) 查看。
重启服务后通过 ss -nutlp | grep ntp 查看服务是否正常监听
如果具有 123 端口上的 udp 报文监听则说明服务正常运行。
接下来使用另一台客户机与此主机进行同步测试。这台主机为另一台服务器,运行 Ubuntu 20.04 LTS
也可使用 chrony 使用和提供 NTP 服务,此处不再赘述,RHEL 8 中的软件源现在默认自带 chrony 配置与 ntpd 大同小异。
chrony
作为服务器
chrony 配置对比 ntpd 更为简单
对于 Debian,配置文件存放在 /etc/chrony/chrony.conf
仅需要简单的使用 allow 即可
如果再简单一点,允许所有主机与其同步时间,只要
需要使用本地时间的场合,也只需要简单的加一句 local 即可
客户端
正常在配置文件里写入 server pool.ntp.org iburst
查看当前时间服务器使用 chronyc sources
正常情况下 Chrony 会步进同步时钟,其与 NTPd 的工作方式很不相同,并没有一个真正意义上与 ntpdate 作用类似的强制同步方式
但如果需要的话,使用 chronyc -a makestep
如果 chronyd 没有运行,正如 ntpdate 使用的那种情况,则可以使用 chronyd -q 'server pool.ntp.org iburst' 手工同步时间。
参考资料:[ArchWiki:Network Time Protocol daemon (简体中文)](https://wiki.archlinux.org/index.php/Network_Time_Protocol_daemon_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87))
Red Hat Documentation:CONFIGURING NTP USING THE CHRONY SUITE
最后更新于
这有帮助吗?