k8s pod时区更改
一、问题所在
在K8S里启动一个容器,该容器的设置的时区是UTC0,但是对于很多客户而言,其主机环境并不在UTC0。例如中国客户在UTC8。如果不把容器的时区和主机主机设置为一致,则在查找日志等时候将非常不方便,也容易造成误解。
二、解决方法
1、挂载服务器的时区
[root@k8s-m ~]# cat demo-pod.yaml apiVersion: v1 kind: Pod metadata: name: nginx-pod namespace: default labels: app: my-pod spec: containers: - name: my-pod image: nginx volumeMounts: - name: host-time mountPath: /etc/localtime readOnly: true volumes: - name: host-time hostPath: path: /etc/localtime
2、传递变量
[root@k8s-m ~]# cat time-pod.yaml apiVersion: v1 kind: Pod metadata: name: pod-env-tz spec: containers: - name: ngx-time image: nginx:latest env: - name: TZ value: Asia/Shanghai
3、重新构建镜像,做镜像是把镜像的时区改了就行
4、修改apiserver的配置清单,用Pod Pres方式更改所有容器的时区
(1)、修改kube-apiserver.yaml文件开启PodPreset
#在末尾添加以下内容
- --runtime-config=settings.k8s.io/v1alpha1=true
#再在enable-admission-plugins=NodeRestriction下加一个PodPreset
- --enable-admission-plugins=NodeRestriction,PodPreset
[root@master ~]# cat -n /etc/kubernetes/manifests/kube-apiserver.yaml|grep runtime-config=settings.k8s.io/v1alpha1 42 - --runtime-config=settings.k8s.io/v1alpha1=true [root@master ~]# cat -n /etc/kubernetes/manifests/kube-apiserver.yaml|grep enable-admission-plugins=NodeRestriction 20 - --enable-admission-plugins=NodeRestriction,PodPreset
(2)、创建Shanghai时区的PodPreset(仅创建了PodPreset资源的namespace名称空间中的资源支持修改的时区)
#创建PodPreset [root@master ~]# cat time-PodPreset.yaml apiVersion: settings.k8s.io/v1alpha1 kind: PodPreset metadata: name: tz-env namespace: default #default的namespace空间中支持Asia/Shanghai时区 spec: selector: matchLabels: env: - name: TZ value: Asia/Shanghai #导入 [root@master ~]# kubectl apply -f time-PodPreset.yaml podpreset.settings.k8s.io/tz-env created
(3)、创建新pod查看时间
#创建新pod查看时间 [root@master ~]# kubectl apply -f 2demo-pod.yaml pod/nginx-pod2 created [root@master ~]# kubectl exec -it nginx-pod2 date kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead. Sat Feb 27 16:00:01 CST 2021
(4)、测试在kube-system名称空间中创建pod查看除default名称空间外是否还是UTC时区
只有创建了PodPreset的namespace中的资源的时区改变了
#在其他namespace名称空间中创建pod测试时区是否改变 [root@master ~]# kubectl apply -f demo-pod.yaml -n kube-system pod/nginx-pod created [root@master ~]# kubectl get pod -n kube-system nginx-pod NAME READY STATUS RESTARTS AGE nginx-pod 1/1 Running 0 24s [root@master ~]# kubectl -n kube-system exec -it nginx-pod date kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead. Sat Feb 27 08:02:15 UTC 2021