本文主要围绕 Linux 服务器时间同步失败的问题展开讨论,以 Ubuntu 和 CentOS 系统为例,提供几种测试和解决方法。
常见错误
1 | Timed out waiting for reply from ... (...) |
1 | chronyd: No suitable source for synchronisation |
NTP 被屏蔽
如果服务器主机出现了时间同步失败的问题,首先应考虑是否是主机商屏蔽了 NTP 数据包,导致系统无法同步时间。一般情况下,可发送工单进行询问以做确认。
客服可能会提供一个可用的 NTP 服务器地址,接下来更改同步时间的软件设置,改为使用该地址同步即可。
Ubuntu
Ubuntu 18.04 默认使用 timesyncd
来同步时间。
编辑配置文件:
1 | sudo vim /etc/systemd/timesyncd.conf |
替换 NTP 服务器,例如为 ntp.ubuntu.com
:
/etc/systemd/timesyncd.conf
1 2 | [Time] NTP=ntp.ubuntu.com |
保存文件后执行:
1 2 3 4 | sudo systemctl daemon-reload sudo timedatectl set-ntp off sudo timedatectl set-ntp on sudo systemctl status systemd-timesyncd |
设置时区为 UTC 的方法:
1 | sudo dpkg-reconfigure tzdata |
CentOS
CentOS 8 默认使用 chronyd
来同步时间。
编辑配置文件:
1 | vim /etc/chrony.conf |
更换 NTP 服务器,例如为 2.centos.pool.ntp.org
:
/etc/chrony.conf
1 | pool 2.centos.pool.ntp.org iburst |
也可手动更新:
1 2 3 | sudo systemctl stop chronyd sudo chronyd -q 'server 2.centos.pool.ntp.org iburst' sudo systemctl start chronyd |
设置时区为 UTC 的方法:
1 | sudo timedatectl set-timezone UTC |
其他方法
除更换为可用 NTP 服务器外,还有其他方式,例如使用 htpdate
等,可自行搜索使用方法。
下面介绍另外一种简便方法,适用于时间精度要求不高的场景,示例中系统用户名为 sammy
:
1 2 | mkdir -p ~/scripts vim ~/scripts/time.sh |
在文件中添加如下内容:
~/scripts/time.sh
1 2 3 4 | #!/bin/bash curl http://time.akamai.com/?iso | xargs date -s hwclock -w |
或者添加如下内容(中国大陆适用),需要安装 jq
软件包:
~/scripts/time.sh
1 2 3 4 5 6 | #!/bin/bash the_date=$(curl -s 'http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp' | jq -r '.data.t') the_date=${the_date::-3} date -s @$the_date hwclock -w |
设置每五分钟执行一次:
1 | sudo crontab -e |
在 cron
文件顶部中添加:
1 2 | MAILTO="" */5 * * * * /bin/bash /home/sammy/scripts/time.sh |
查看执行日志:
1 | journalctl _COMM=crond |
本文完。