我的docker随笔23:修改容器时区和添加中文支持

许多 docker 镜像没有时区,默认是0时区,对于日志的时间显示,可能不太友好。另外有些镜像无法输出中文,也不太好友。本文以 busybox 为例,尝试解决此类问题。

时区支持

运行busybox:

1
docker run -itd --rm --name busybox latelee/busybox

1
2
3
4
5
6
docker exec -it busybox date
Fri Mar 20 05:13:50 UTC 2020

docker exec -it busybox cat /etc/localtime
TZif2UTCTZif2UTC
UTC0

查看本地时区文件:

1
2
3
4
5
6
7
8
9
ls -l /etc/localtime 
lrwxrwxrwx 1 root root 33 Dec 17 21:50 /etc/localtime -> /usr/share/zoneinfo/Asia/Shanghai
ls -l /usr/share/zoneinfo/Asia/Shanghai
lrwxrwxrwx 1 root root 6 Oct 3 05:06 /usr/share/zoneinfo/Asia/Shanghai -> ../PRC
cat /usr/share/zoneinfo/PRC
TZif2
Ӌ{
pMTCDTCST
CST-8

拷贝本地时区文件:

1
docker cp /usr/share/zoneinfo/PRC busybox:/etc/localtime

查看:

1
2
docker exec -it busybox date
Fri Mar 20 13:14:27 CST 2020

如果在 k8s 中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
apiVersion: v1
kind: Pod
metadata:
name: busybox-pod1
labels:
app: busybox
spec:
containers:
- name: busybox1
image: latelee/busybox
imagePullPolicy: IfNotPresent
command: ["sh", "-c", "sleep 3600"]
volumeMounts:
- mountPath: /test111
name: host-volume
- mountPath: /etc/localtime
name: time-zone
volumes:
- name: host-volume
hostPath:
path: /data
- name: time-zone
hostPath:
path: /etc/localtime

字符编码

进入容器,设置环境变量:

1
2
3
export LANG=C.UTF-8 
export LANGUAGE=C.UTF-8
export LC_ALL=C.UTF-8

在 Dockerfile 文件中可如此使用:

1
2
3
ENV LANG C.UTF-8 
ENV LANGUAGE C.UTF-8
ENV LC_ALL C.UTF-8

设置前后的输出对比:

1
2
3
4
5
6
/ # æ?????
sh: æ??是中文: not found


/ # 我是中文
sh: 我是中文: not found

制作

将该容器保存为新的镜像即可。另外可用 Dockerfile 制作。

总结

是否添加支持,取决于实际需求,如果所有基础镜像均是自己维护,建议添加。