update at 2024-04-23 15:18:07
parent
3167463b87
commit
5f6c50906a
|
@ -4,7 +4,36 @@
|
|||
|
||||
业务程序在使用时间的时候(比如打印日志),没有指定时区,使用的系统默认时区,而基础镜像一般默认使用 UTC 时间,程序输出时间戳的时候,就与国内的时间相差 8 小时,如何使用国内的时间呢?本文教你如何解决。
|
||||
|
||||
## 最佳实践:使用多阶段构建拷贝时区文件
|
||||
## 方案一:指定 TZ 环境变量
|
||||
|
||||
很多编程语言都支持 `TZ` 这个用于设置时区的环境变量,可以在部署工作负载的时候,为容器指定该环境变量,示例:
|
||||
|
||||
```yaml showLineNumbers
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: app
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: app
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: app
|
||||
spec:
|
||||
containers:
|
||||
- name: app
|
||||
image: app
|
||||
env:
|
||||
# highlight-start
|
||||
- name: TZ
|
||||
value: Asia/Shanghai
|
||||
# highlight-end
|
||||
```
|
||||
|
||||
## 方案二:使用多阶段构建拷贝时区文件
|
||||
|
||||
centos 基础镜像内置了时区文件,可以将里面国内的时区文件拷贝到业务镜像中的 `/etc/localtime` 路径,表示系统默认时区是国内时区:
|
||||
|
||||
|
@ -13,5 +42,40 @@ FROM centos:latest
|
|||
|
||||
FROM ubuntu:22.10
|
||||
|
||||
# highlight-next-line
|
||||
COPY --from=0 /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
|
||||
```
|
||||
|
||||
## 方案三:挂载主机时区配置到容器(不推荐)
|
||||
|
||||
```yaml showLineNumbers
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: app
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: app
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: app
|
||||
spec:
|
||||
containers:
|
||||
- name: app
|
||||
image: app
|
||||
volumeMounts:
|
||||
# highlight-start
|
||||
- name: tz
|
||||
mountPath: /etc/localtime
|
||||
# highlight-end
|
||||
volumes:
|
||||
# highlight-start
|
||||
- name: tz
|
||||
hostPath:
|
||||
path: /etc/localtime
|
||||
# highlight-end
|
||||
```
|
||||
|
||||
|
|
Loading…
Reference in New Issue