基础概念
硬件时钟:芯片时钟,有计算机主板上的时钟芯片提供
系统时钟:操作系统提供的时钟
备注:在服务器开机启动的时候系统时钟会去读取硬件时钟作为初始时间,如果硬件时钟不准确,就会导致服务器时间不准
linux下常见时钟命令
date
hwclock
timedatectl
date命令
date #直接执行,查看系统时间
date -s "2023-2-21 11:11:11" #手动修改时间
hwclock -w #同步系统时间到硬件时钟
hwclock -s #同步硬件时间到系统时钟
timedatectl
[root@k8sworker06 ~]# timedatectl
Local time: Tue 2023-02-21 10:56:22 CST #本地时间
Universal time: Tue 2023-02-21 02:56:22 UTC #世界协调时间,默认比北京时间慢八小时
RTC time: Tue 2023-02-21 02:56:23 #硬件时钟
Time zone: Asia/Shanghai (CST, +0800) #服务器时区,东八区
NTP enabled: yes #是否与网络时钟同步,涉及到两个服务ntpd和chronyd(两个服务开启一个即可)
NTP synchronized: yes #是否已经同步过网络时间
RTC in local TZ: no #硬件时钟是否与本地之间同步
DST active: n/a #是否开启夏令时,默认不开启
timedatectl #直接执行,查看系统时种设置
timedatectl set-time "2023-2-21 11:11:11" #设置系统时种
timedatectl set-ntp true/false #控制是否与网络时间同步
timedatectl set-timezone "Asia/Shanghai" #设置时区为上海
timedatectl list-timezones #列出所有时区
timedatectl set-local-rtc 1 #将RTC设置为本地时间
timedatectl set-local-rtc 0 #将RTC设置为UTC
使用ntp进行时钟同步
yum install -y ntp #安装ntp服务
systemctl start ntpd #开启ntp服务
systemctl enable ntpd #开启ntp服务开机自启动
vi /etc/ntp.conf
#注释下面4行
#server 0.centos.pool.ntp.org iburst
#server 1.centos.pool.ntp.org iburst
#server 2.centos.pool.ntp.org iburst
#server 3.centos.pool.ntp.org iburst
#替换成中国时间服务器
#http://www.pool.ntp.org/zone/cn
server 0.cn.pool.ntp.org
server 1.cn.pool.ntp.org
server 2.cn.pool.ntp.org
server 3.cn.pool.ntp.org
date -R
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime #修改时区
使用chrony服务时间同步
yum -y install chrony #安装chrony服务
systemctl start chrony #开启chrony服务
systemctl enable chrony #开启chrony服务开机自启动
date -R #查看服务器系统时间