Linux配置ntp时间同步服务
1、首先检查系统中是否安装ntp包:
rpm -q ntp
2、执行命令在线安装ntp:
yum -y install ntp
3、使用命令查看ntp是否设置为开启启动状态:
systemctl is-enabled ntpd
4、现在设置开机自启动:
chkconfig ntpd on 或者 systemctl enable ntpd
5、设置成功后,ntp服务并不能立即启动,而是在下次重启之后启动,手动启动ntp:
systemctl start ntpd.service
6、启动之后,查看ntp服务的123端口已经使用:
netstat -an | grep 123
7、 执行ps也可以看到ntp进程也已经启动:
ps -ef | grep ntpd
8、默认情况下ntp是从外网时间服务器来更新时间的,在集群中使用只要保证集群中所有的服务器时间一致即可,所以先配置其中一台服务器为时间服务器,其他服务器相对来说为这台时间服务器的客户端,从时间服务器上获取时间数据,从而避免联网,可用性更高
9、首先是时间服务器配置:
时间服务器的IP:172.16.12.89
执行
vim /etc/ntp.conf
打开ntp配置文件,找到server指定时间服务器的位置,这些条都注释掉;然后添加下面2行固定配置:
server 127.127.1.0
fudge 127.127.1.0 stratum 10
10、然后在restrict指定的两行下面追加:
restrict 192.168.1.1 mask 255.255.252.0 nomodify notrap
这个配置根据自己的网关和网段配置,只要能保证局域网主机通信就可以,比如这里子网掩码为255.255.252.0那么网段配置192.168.0.0也可以,只是通信的范围不太一样,总之这个配置就是授权局域网内能从本地同步时间的主机范围。
参考:
配置下游服务器可以使用该服务的IP网段(192.168.0.0-192.168.0.255)
restrict 127.0.0.1
restrict 192.168.0.0 mask 255.255.255.0 nomodify
配置上游NTP服务器IP地址
server cn.pool.ntp.org
#外部时间服务器不可用时,以本地时间作为时间服务
server 127.127.1.0 #local clock
fudge 127.127.1.0 stratum 3
logfile /var/log/ntpstats/ntpd.log # 定义ntp日志目录
pidfile /var/run/ntp.pid # 定义pid路径
11、配置好之后,保存并退出,执行 重启ntp服务即可
systemctl restart ntpd.service
12、然后是其他服务器的配置,这里相当于客户端的配置:
同样执行上面的一些命令对ntp进行安装、启动、自启配置、状态查看等操作,配置文件依然是:/etc/ntp.conf,打开进行如下配置:
同样注释默认的server服务器,添加一行指定时间服务器位置:因为上面时间服务器地址是172.16.12.89
server 172.16.12.89
配置好之后,保存,重启ntp服务即可
所有客户端都进行以上配置,都启动之后,集群会自动定期进行服务的同步(启动后3-5分钟才会同步),这样集群的时间就保持一致了
13、 另外如果想要手动同步某一台机器的时间,那么可以依次执行下面命令实现:
systemctl stop ntpd # 先停止服务,否则ntp socket会被占用
ntpdate 172.16.12.89 # 手动执行同步
systemctl start ntpd # 继续启动服务
ntp同步状态查看
- ntpstat
ntpstat 命令查看时间同步状态,这个一般需要5-10分钟后才能成功连接和同步。所以,服务器启动后需要稍等下。
刚启动的时候,一般是:
ntpstat
unsynchronised
time server re-starting
polling server every 8 s
连接并同步后
ntpstat
synchronised to NTP server (172.16.12.89) at stratum 4
time correct to within 1230 ms
polling server every 64 s - ntpq -p
ntp校时服务器:
server cn.pool.ntp.org
server asia.pool.ntp.org
server cn.ntp.org.cn
server ntp.aliyun.com
server time.asia.apple.com
ntpd卸载重装
备份旧版本的配置文件
cp -ar /etc/ntp /etc/ntp.bak
cp /etc/ntp.conf /etc/ntp.conf.bak
cp /etc/init.d/ntpd /etc/init.d/ntpd.bak
cp /etc/sysconfig/ntpd /etc/sysconfig/ntpd.bak
cp /etc/sysconfig/ntpdate /etc/sysconfig/ntpdate.bak
卸载yum安装的ntpd服务
yum erase ntp ntpdate