本文介绍如何搭建和配置 NTP 服务器,确保网络时间同步的准确性和可靠性。
准备工作
在开始之前,需要准备一台运行 Linux 或类 Unix 操作系统的服务器。确保服务器具备以下条件:
- 稳定的网络连接
- root 或 sudo 权限
- 一个静态公网 IP 地址或域名解析
安装 NTP 服务
CentOS/RHEL 系统
使用以下命令安装 NTP 服务:
sudo yum install ntp
Ubuntu/Debian 系统
使用以下命令安装 NTP 服务:
sudo apt-get install ntp
配置 NTP 服务
编辑 NTP 配置文件
使用文本编辑器打开 NTP 配置文件:
sudo nano /etc/ntp.conf
在文件末尾添加以下配置,选择合适的 NTP 服务器作为参考源:
server 0.pool.ntp.org iburst
server 1.pool.ntp.org iburst
server 2.pool.ntp.org iburst
server 3.pool.ntp.org iburst
添加本地网络接口配置,允许内部设备时间同步:
interface leap-tick
interface ignore
interface lo
restrict default kod nomodify notrap nopeer noquery
restrict 127.0.0.1 mask 255.0.0.0 kod nomodify notrap nopeer noquery
restrict 192.168.0.0 mask 255.255.0.0 kod nomodify notrap nopeer noquery
设置时区
确保时区配置正确:
sudo ntpdate -u pool.ntp.org
启动和启用 NTP 服务
启动 NTP 服务并设置为开机自启:
sudo systemctl start ntp
sudo systemctl enable ntp
检查服务状态:
sudo systemctl status ntp
验证 NTP 同步
使用以下命令查看当前时间同步情况:
sudo ntpstat
或使用更详细的命令:
sudo ntpdc -c info
正常情况下,stratum 值应为 1 或 2,offset 值应接近 0。
防火墙配置
如果服务器启用了防火墙,需要开放 NTP 端口(默认为 123 UDP):
iptables (CentOS/RHEL)
sudo iptables -A INPUT -p udp --dport 123 -j ACCEPT
sudo service iptables save
ufw (Ubuntu/Debian)
sudo ufw allow 123/udp
sudo ufw enable
客户端配置
客户端设备配置 NTP 服务非常简单,通常在操作系统级别的时钟配置中已默认集成。例如,在 Ubuntu 系统中,客户端会自动从网络同步时间:
sudo timedatectl set-ntp true