我的docker隨筆23:修改容器時區和添加中文支持

許多 docker 鏡像沒有時區,默認是0時區,對於日誌的時間顯示,可能不太友好。另外有些鏡像無法輸出中文,也不太好友。本文以 busybox 爲例,嘗試解決此類問題。

時區支持

運行busybox:

 docker run -itd --rm --name busybox latelee/busybox 
docker exec -it busybox date
Fri Mar 20 05:13:50 UTC 2020

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

查看本地時區文件:

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

拷貝本地時區文件:

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

查看:

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

如果在 k8s 中

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

字符編碼

進入容器,設置環境變量:

export LANG=C.UTF-8 
export LANGUAGE=C.UTF-8
export LC_ALL=C.UTF-8

在 Dockerfile 文件中可如此使用:

ENV LANG C.UTF-8 
ENV LANGUAGE C.UTF-8
ENV LC_ALL C.UTF-8

設置前後的輸出對比:

/ # æ?????
sh: æ??是中文: not found


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

製作

將該容器保存爲新的鏡像即可。另外可用 Dockerfile 製作。

總結

是否添加支持,取決於實際需求,如果所有基礎鏡像均是自己維護,建議添加。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章