插件窝 干货文章 Linux 上设置自己的公共时间服务器

Linux 上设置自己的公共时间服务器

NTP 服务器 sudo bash 214    来源:    2025-05-21

在Linux上设置公共NTP时间服务器指南

概述

NTP(Network Time Protocol)是用于同步计算机系统时钟的协议。将你的Linux服务器配置为公共NTP服务器可以让其他设备从你的服务器获取准确的时间。

准备工作

  1. 确保服务器有稳定的网络连接
  2. 服务器最好有静态IP地址
  3. 确保服务器时间已经同步(可以使用ntpdatechrony临时同步)

安装NTP服务

对于基于Debian/Ubuntu的系统:

sudo apt update
sudo apt install ntp

对于基于RHEL/CentOS的系统:

sudo yum install ntp
# 或对于较新版本
sudo dnf install ntp

配置NTP服务器

编辑NTP配置文件:

sudo nano /etc/ntp.conf

基本配置示例:

# 使用公共NTP池服务器作为上游
server 0.pool.ntp.org
server 1.pool.ntp.org
server 2.pool.ntp.org
server 3.pool.ntp.org

# 允许本地网络客户端访问
restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap

# 允许所有客户端访问(公共服务器)
restrict default kod nomodify notrap nopeer noquery
restrict -6 default kod nomodify notrap nopeer noquery

# 允许本地主机有所有权限
restrict 127.0.0.1
restrict -6 ::1

# 启用日志
logfile /var/log/ntp.log

高级配置选项:

  • nomodify - 防止客户端修改服务器配置
  • notrap - 防止客户端使用陷阱服务
  • nopeer - 防止对等体形成
  • noquery - 防止NTPQ和NTPDC查询

启动并启用NTP服务

sudo systemctl start ntpd
sudo systemctl enable ntpd

防火墙配置

允许NTP端口(123/UDP)通过防火墙:

sudo ufw allow 123/udp  # 对于UFW
# 或
sudo firewall-cmd --add-service=ntp --permanent  # 对于firewalld
sudo firewall-cmd --reload

验证NTP服务器

  1. 检查NTP服务状态:
sudo systemctl status ntpd
  1. 查看NTP对等体状态:
ntpq -p
  1. 从另一台机器测试你的NTP服务器:
ntpdate -q your.server.ip

优化建议

  1. 考虑服务器负载: 公共NTP服务器可能会收到大量请求,确保服务器有足够资源

  2. 使用NTP池项目: 如果你的服务器稳定可靠,可以考虑加入NTP池项目

    • 访问: https://www.pool.ntp.org/
  3. 监控: 设置监控以确保NTP服务正常运行

  4. 安全: 定期检查日志,确保没有异常访问

维护

  1. 定期检查日志:
tail -f /var/log/ntp.log
  1. 更新NTP软件包:
sudo apt update && sudo apt upgrade ntp  # Debian/Ubuntu
sudo yum update ntp                     # RHEL/CentOS

通过以上步骤,你的Linux服务器就可以作为公共NTP时间服务器运行了。