Docker容器的时区设置

Docker容器的时区设置,一直以来都是个简单而且重要的问题。下面笔者以CentOS 7.5.1804作为容器宿主机为例,分别介绍如何在原生Docker容器和Kubernetes的Pod中正确设置时区。

Node设置正确时区(以CentOS 7.5.1804 为例)

1
2
3
timedatectl list-timezones
timedatectl set-timezone Asia/Shanghai
timedatectl status | grep 'Time zone'

提示:这里相当于为Docker Container和Kubernetes Pod的宿主机设置正确的时区,需要优先配置完成。

Docker Container 与 Node同步时区设置

1
docker run -it -v /etc/localtime:/etc/localtime --rm alpine:3.8 /bin/sh

提示:上述命令注意-v参数的部分。
总结:经测试验证,alpine:3.8、centos:7.5.1804和ubuntu:16.04处理方式相同。

Kubernetes Pod 与 Node同步时区设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
apiVersion: v1
kind: Pod
metadata:
name: alpine
labels:
app: alpine
spec:
containers:
- image: alpine:3.8
imagePullPolicy: IfNotPresent
name: alpine
command:
- sleep
- "3600"
volumeMounts:
- name: tz-config
mountPath: /etc/localtime
readOnly: true
restartPolicy: Always
volumes:
- name: tz-config
hostPath:
path: /etc/localtime

提示:上述YAML注意volumes和volumeMounts部分。
总结:经测试验证,alpine:3.8、centos:7.5.1804和ubuntu:16.04处理方式相同。

Docker Container 和 Kubernetes Pod 通用 与 Node同步时区设置

该方式在需要构建Docker Image的时候,即修改Docker Image的默认时区设置。

Alpine Linux 3.8 Dockerfile Example

1
2
3
4
5
6
FROM alpine:3.8

MAINTAINER wangxin_0611@126.com

RUN apk --no-cache add tzdata && \
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

Ubuntu Linux 16.04 Dockerfile Example

1
2
3
4
5
6
7
FROM ubuntu:16.04

MAINTAINER wangxin_0611@126.com

RUN apt-get update && \
apt-get install -y tzdata && \
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

CenOS Linux 7.5.1804 Dockerfile Example

1
2
3
4
5
FROM centos:7.5.1804

MAINTAINER wangxin_0611@126.com

RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

参考资料:
https://blog.csdn.net/qq_34924407/article/details/82057080
https://blog.csdn.net/u013201439/article/details/79436413