在 Kubernetes 中,直接设置环境变量:
- name: TZ
value: Asia/Shanghai
但在大多数精简镜像(如 alpine
、distroless
)里不会生效,因为这些镜像缺少时区数据库(tzdata
),导致容器无法解析时区信息。
TZ=Asia/Shanghai
环境变量无效,date
命令输出仍是 UTC。/usr/share/zoneinfo/Asia/Shanghai
和 /etc/localtime
。/etc/localtime
文件后,时间仍显示为 UTC。如果可以改镜像,在构建时安装 tzdata:
Debian/Ubuntu 基础镜像
RUN apt-get update && apt-get install -y tzdata
Alpine 基础镜像
RUN apk add --no-cache tzdata
安装完成后即可通过 TZ
环境变量或 /etc/localtime
控制时区。
在 Pod 里挂载宿主机的 zoneinfo 时区库和 localtime 文件,无需修改镜像:
volumeMounts:
- name: tz-config
mountPath: /usr/share/zoneinfo
readOnly: true
- name: tz-localtime
mountPath: /etc/localtime
readOnly: true
volumes:
- name: tz-config
hostPath:
path: /usr/share/zoneinfo
- name: tz-localtime
hostPath:
path: /etc/localtime
这种方式适用于任何镜像,容器时间会与宿主机保持一致(如宿主机设置为 Asia/Shanghai,则容器内 date
也显示 CST)。
进入容器执行:
date
date -R
ls -l /etc/localtime
strings /etc/localtime | grep -E "Shanghai|CST"
预期结果:
date
输出北京时间(CST, UTC+8)。/etc/localtime
是一个挂载文件。strings /etc/localtime
能看到 Shanghai
或 CST
。/usr/share/zoneinfo
和 /etc/localtime
。tzdata
包。/etc/timezone
不是必须的,没有它不影响时区设置。用 nginx
容器来演示时区挂载配置。你可以直接应用到集群里测试。
apiVersion: v1
kind: Pod
metadata:
name: nginx-tz-test
labels:
app: nginx-tz-test
spec:
containers:
- name: nginx
image: nginx:1.25
command: ["/bin/sh", "-c", "while true; do date; sleep 30; done"]
volumeMounts:
- name: tz-config
mountPath: /usr/share/zoneinfo
readOnly: true
- name: tz-localtime
mountPath: /etc/localtime
readOnly: true
volumes:
- name: tz-config
hostPath:
path: /usr/share/zoneinfo
- name: tz-localtime
hostPath:
path: /etc/localtime
应用 Pod
kubectl apply -f nginx-tz-test.yaml
进入容器查看时间
kubectl exec -it nginx-tz-test -- date
预期输出:北京时间(CST, UTC+8)。
查看日志
kubectl logs -f nginx-tz-test
你会看到容器里每 30 秒输出一次北京时间。
date
输出为 CST
,说明挂载的 /usr/share/zoneinfo
和 /etc/localtime
已生效。UTC
,检查宿主机是否正确设置了时区(timedatectl
应显示 Asia/Shanghai
)。apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-tz-deployment
labels:
app: nginx-tz
spec:
replicas: 3
selector:
matchLabels:
app: nginx-tz
template:
metadata:
labels:
app: nginx-tz
spec:
containers:
- name: nginx
image: nginx:1.25
command: ["/bin/sh", "-c", "while true; do date; sleep 30; done"]
volumeMounts:
- name: tz-config
mountPath: /usr/share/zoneinfo
readOnly: true
- name: tz-localtime
mountPath: /etc/localtime
readOnly: true
volumes:
- name: tz-config
hostPath:
path: /usr/share/zoneinfo
- name: tz-localtime
hostPath:
path: /etc/localtime
部署
kubectl apply -f nginx-tz-deployment.yaml
查看 Pod
kubectl get pods -l app=nginx-tz
进入不同 Pod 验证时间
kubectl exec -it <pod-name> -- date
查看日志
kubectl logs -f <pod-name>
→ 所有 Pod 都应该打印北京时间(CST, UTC+8)。
date
输出都是 CST,说明时区挂载生效。