K8s Pod与宿主机时区不同步

在K8s集群中运行的容器默认会使用UTC时间,即北京时间为凌晨3点时,容器时间为晚上7点,中间会有8小时时差。而有些分布式系统对于时间极为敏感,不允许出现时间误差

这里我们构建一个Nginx镜像,查看构建前的时间

1
2
3
4
5
6
7
8
9
10
apiVersion: v1
kind: Pod
metadata:
  name: time-nginx
spec:
  containers:
  - name: time-nginx
    image: nginx
    args: [/bin/sh, -c,
            'i=0; while true; do echo "$i: $(date)"; i=$((i+1)); sleep 1; done']

创建完Pod后查看一下时间

1
2
3
4
kubectl  logs -f time
337: Fri May  1 19:01:30 UTC 2020
338: Fri May  1 19:01:31 UTC 2020
339: Fri May  1 19:01:32 UTC 2020

解决问题

首先要确保宿主机时间同步

1
2
3
4
5
6
7
8
timedatectl set-timezone Asia/Shanghai
 
#将当前的 UTC 时间写入硬件时钟
timedatectl set-local-rtc 0
 
#重启依赖于系统时间的服务
systemctl restart rsyslog
systemctl restart crond

目前解决Pod和宿主机时间不一致有以下集中解决方案

1、通过定制Dockerfile添加时区

2、通过将时区文件挂在到Pod中

3、通过环境变量定义时区

4、进入容器内修改时区,或者docker cp时区进去

5、网上资料还有通过PodPreset的方式

一、通过定制Dockerfile添加时区

1
2
3
4
5
6
7
8
9
10
11
12
13
$ cat Dockerfile.date
FROM centos
      
RUN rm -f /etc/localtime \
&& ln -sv /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
&& echo "Asia/Shanghai" > /etc/timezone
      
# 构建容器镜像
$ docker build -t centos7-date:test -f Dockerfile.date .
      
$ docker run -it centos7-date:test /bin/sh
sh-4.2# date
Wed Mar  6 16:40:01 CST 2019

二、通过将时区文件挂在到Pod中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
cat time-mount.yaml
apiVersion: v1
kind: Pod
metadata:
  name: time
spec:
  containers:
  - name: time
    image: nginx
    args: [/bin/sh, -c,
            'i=0; while true; do echo "$i: $(date)"; i=$((i+1)); sleep 1; done']
    volumeMounts:
      - name: timezone
        mountPath: /etc/localtime
  volumes:
    - name: timezone
      hostPath:
        path: /usr/share/zoneinfo/Asia/Shanghai

通过命令查看,/etc/localtime的目录实际上就是个软连接

如果需要系统修改时区,那么只需要将时区文件覆盖到/etc/localtime,前提是宿主机设置好上海的时区。

1
2
ll /etc/localtime
lrwxrwxrwx. 1 root root 35 Apr 20 00:11 /etc/localtime -> ../usr/share/zoneinfo/Asia/Shanghai

三、通过环境变量定义时区

1
2
3
4
5
6
7
8
9
10
11
12
13
14
cat time.yaml
apiVersion: v1
kind: Pod
metadata:
  name: time-nginx
spec:
  containers:
  - name: time-nginx
    image: nginx
    args: [/bin/sh, -c,
            'i=0; while true; do echo "$i: $(date)"; i=$((i+1)); sleep 1; done']
    env:
    - name: TZ
      value: Asia/Shanghai

四、进入容器内修改时区

1
2
3
4
5
6
kubectl exec -it time-nginx /bin/sh
# date
Fri May  1 19:28:33 UTC 2020
# rm -f /etc/localtime && ln -sv /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
# date
Sat May  2 03:29:11 CST 2020

 

posted @   凡人半睁眼  阅读(1164)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
· Manus的开源复刻OpenManus初探

阅读目录(Content)

此页目录为空

点击右上角即可分享
微信分享提示