Linux系统时区时间不准?如何进行校时?

封面在使用服务器时,时间同步很重要,因为很多服务依赖时间,比如数据库、缓存、日志、监控等等。

但是随着运行时间的增长,时间同步的精度会越来越差,因此,建议将服务器的时钟同步到公网时间服务器。

设置时区

1
2
3
4
5
6
7
8
9
# 查看当前时区
timedatectl

# 查看可用时区
#timedatectl list-timezones | grep -i shanghai
timedatectl list-timezones

# 设置时区为上海
timedatectl set-timezone Asia/Shanghai

安装chrony校时

1
2
3
4
5
# CentOS
yum install chrony -y

# Ubuntu/Debian
apt install chrony -y

配置NTP服务器

1
2
3
4
5
# CentOS
vim /etc/chrony.conf

# Ubuntu/Debian
vim /etc/chrony/chrony.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 使用阿里云NTP服务器(中国用户推荐)
server ntp.aliyun.com iburst
server ntp1.aliyun.com iburst
server ntp2.aliyun.com iburst

# 或使用腾讯云NTP服务器
server ntp.tencent.com iburst

# 或使用国家授时中心服务器
server ntp.ntsc.ac.cn iburst

# 或自定义内部NTP服务器
#server 192.168.1.100 iburst

# 允许同步的网络范围(可选,用于内部NTP服务器)
allow 192.168.0.0/16

# 设置时间同步源为本地硬件时钟(当外部源不可用时)
local stratum 10

重启chrony服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 启动chronyd服务(这个才是负责同步时间的)
sudo systemctl start chronyd

# 设置开机自启
sudo systemctl enable chronyd

# 检查服务状态
sudo systemctl status chronyd

# 重启服务
sudo systemctl restart chronyd


# chronyc只是用来监控和手动控制的工具
chronyc sources # 查看时间源
chronyc tracking # 查看同步状态
chronyc makestep # 手动强制同步

检查和管理时间同步

使用timedatectl命令

1
2
3
4
5
6
7
8
9
# 查看时间状态
timedatectl status

# 开启/关闭NTP时间同步
sudo timedatectl set-ntp yes # 开启
sudo timedatectl set-ntp no # 关闭

# 查看时间同步状态
timedatectl show-timesync

使用chronyc命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 查看时间源状态
chronyc sources -v

# 查看时间源统计信息
chronyc sourcestats -v

# 手动同步时间
sudo chronyc makestep

# 查看NTP服务器跟踪状态
chronyc tracking

# 检查chrony是否正常运行
chronyc activity

chronyc强制同步

1
2
3
4
5
6
7
# 对于chrony
sudo chronyc -a makestep

# 停止服务,手动同步,然后重启
sudo systemctl stop chrony
sudo chronyd -q 'server ntp.aliyun.com iburst'
sudo systemctl start chrony

推荐的中国NTP服务器列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 阿里云
ntp.aliyun.com
ntp1.aliyun.com
ntp2.aliyun.com
ntp3.aliyun.com
ntp4.aliyun.com
ntp5.aliyun.com
ntp6.aliyun.com
ntp7.aliyun.com

# 腾讯云
ntp.tencent.com
time1.cloud.tencent.com
time2.cloud.tencent.com
time3.cloud.tencent.com
time4.cloud.tencent.com
time5.cloud.tencent.com

# 国家授时中心
ntp.ntsc.ac.cn
ntp1.ntsc.ac.cn
ntp2.ntsc.ac.cn

# 教育网
s1a.time.edu.cn # 北京邮电大学
s1b.time.edu.cn # 清华大学
s1c.time.edu.cn # 北京大学
s1d.time.edu.cn # 东南大学
s1e.time.edu.cn # 清华大学