Linux NTP 时间同步
时间在 Linux 服务器中扮演着重要角色,特别是在银行、股票市场和其他 金融领域。如果我们希望所有 Linux 服务器都拥有正确的时间,那么必须配置一个 NTP 客户端,它将始终从远程 NTP 服务器获取正确的时间,并在需要时进行必要的调整以同步时间。
本文介绍如何在 Linux 服务器上使用传统的 NTP(Network Time Protocol)服务与 NTP 服务器同步时间。
什么是 NTP
NTP(Network Time Protocol)是网络时间协议,用于同步计算机系统时钟。NTP 是 Linux 系统中传统的时间同步解决方案,在较旧的系统版本中广泛使用。
NTP 的主要特点:
- 成熟稳定,经过长期验证
- 支持多种时间源
- 提供高精度的时间同步
- 支持层级(Stratum)结构
- 支持认证机制
注意:从 RHEL 8/CentOS 8 开始,传统的 ntp 包已被 chrony 取代。如果你使用的是较新的系统,建议使用 Chrony 时间同步。本文主要适用于 CentOS 7/RHEL 7 及更早版本的系统。
安装 NTP
Debian/Ubuntu 系统
sudo apt update
sudo apt install -y ntp
RedHat/CentOS 系统
对于 CentOS 7 及更早版本:
sudo yum install -y ntp
注意:CentOS 8/RHEL 8 及更新版本不再提供 ntp 包,请使用 chrony。
Fedora 系统
sudo dnf install -y ntp
验证安装
安装完成后,Linux 系统会增加以下命令和服务:
- ntpdate:用于手动同步时间的命令
- ntpq:NTP 查询程序,用于查询 NTP 服务器状态
- ntpd:NTP 守护进程,负责时间同步服务
验证安装:
# 检查 ntpdate 命令
ntpdate -v
# 检查 ntpd 服务
systemctl status ntpd
# 或
service ntpd status
配置 NTP
NTP 的配置文件通常是 /etc/ntp.conf。
配置文件位置
# 查找配置文件位置
ls -l /etc/ntp.conf
# 查看配置文件内容
cat /etc/ntp.conf
配置文件示例
以下是 CentOS 7 系统的默认配置文件示例:
/etc/ntp.conf
# For more information about this file, see the man pages
# ntp.conf(5), ntp_acc(5), ntp_auth(5), ntp_clock(5), ntp_misc(5), ntp_mon(5).
driftfile /var/lib/ntp/drift
# Permit time synchronization with our time source, but do not
# permit the source to query or modify the service on this system.
restrict default nomodify notrap nopeer noquery
# Permit all access over the loopback interface. This could
# be tightened as well, but to do so would effect some of
# the administrative functions.
restrict 127.0.0.1
restrict ::1
# Hosts on local network are less restricted.
#restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap
# Use public servers from the pool.ntp.org project.
# Please consider joining the pool (http://www.pool.ntp.org/join.html).
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
# Ignore stratum 0 sources
fudge 127.127.1.0 stratum 10
# Enable public key cryptography.
#crypto
includefile /etc/ntp/crypto/pw
# Key file containing the keys and key identifiers used when operating
# with symmetric key cryptography.
keys /etc/ntp/keys
# Specify the key identifiers which are trusted.
#trustedkey 4 8 42
# Specify the key identifier to use with the ntpdc utility.
#requestkey 8
# Specify the key identifier to use with the ntpq utility.
#controlkey 8
# Enable writing of statistics records.
#statistics clockstats cryptostats loopstats peerstats