如何设置Linux时间同步
准确的计时已成为现代软件部署的关键组成部分。无论是确保以正确的顺序记录日志还是正确应用数据库更新,不同步的时间都可能导致错误,数据损坏和其他难以调试的问题。
最新基于systemd
的发行版本都有内置的时间同步功能,由systemd-timesyncd
服务接管。下面是一些相关的操作,帮助我们快速解决时间同步问题。
设置时区(timezone)
通过date
命令我们可以快速查看服务器的时间信息,这里现实的是UTC(Coordinated Universal Time)
时间,当您的基础架构跨越多个时区时,一致地使用UTC时间可以减少系统交互之间的混乱。
date
Tue Sep 4 17:51:49 UTC 2018
如果有不同的要求并需要更改时区,则可以使用timedatectl命令来完成。
先列出一下所有可用时区,找到我们需要的时区,一般国内使用Asia/Shanghai
时区:
timedatectl list-timezones
接下来我们使用timedatectl set-timezone
设置时区
timedatectl set-timezone Asia/Shanghai
我们再查看下系统的时间,已经切换到Shanghai时区了
date
Wed Mar 13 19:06:53 CST 2019
设置时间同步(Time Synchronization)
大多数Linux发行版本使用ntp服务来同步时间,检查下ntp
服务
systemctl status ntp
● ntp.service - Network Time Service
Loaded: loaded (/lib/systemd/system/ntp.service; enabled; vendor preset: enabled)
Active: active (running) since Wed 2019-03-13 19:10:58 CST; 30s ago
Docs: man:ntpd(8)
Main PID: 29753 (ntpd)
Tasks: 2 (limit: 7372)
CGroup: /system.slice/ntp.service
└─29753 /usr/sbin/ntpd -p /var/run/ntpd.pid -g -u 113:119
如果没有对应服务的话,需要先安装ntp服务
- debian/ubuntu
apt -y install ntp
- centos
yum -y install ntp
基于systemd的发行版已经天然集成systemd-timesyncd
在使用systemd-timesyncd
之前,我们需要移除ntp服务
- debian/ubuntu
apt -y purge ntp
- centos
yum -y erase ntp
检查systemd-timesyncd
服务是否已经运行
systemctl status systemd-timesyncd
● systemd-timesyncd.service - Network Time Synchronization
Loaded: loaded (/lib/systemd/system/systemd-timesyncd.service; enabled; vendor preset: enabled)
Active: inactive (dead) since Wed 2019-03-13 19:10:58 CST; 6min ago
Docs: man:systemd-timesyncd.service(8)
Main PID: 35910 (code=exited, status=0/SUCCESS)
Status: "Idle.
如果没运行的话,直接启动就可以了。
systemctl start systemd-timesyncd
使用timedatectl查看系统时间的详细设置情况
timedatectl
Local time: Wed 2019-03-13 19:19:09 CST
Universal time: Wed 2019-03-13 11:19:09 UTC
RTC time: Wed 2019-03-13 11:19:09
Time zone: Asia/Shanghai (CST, +0800)
System clock synchronized: yes
systemd-timesyncd.service active: yes
RTC in local TZ: no
参考链接