Docker容器时间不同步,修改Docker时区

2023-02-13 10:40:25 浏览数 (1)

今天发现日志服务器采集到的某一个系统的日志时间不对,和实际的时间相差了8个小时,我们估计问题是出在容器的时区的设置上。

  1. 进入docker 容器后,查看一下时间:
代码语言:shell复制
#进入容器
docker exec -it xxxx /bin/bash
#查看时间
bash-4.4# date
Mon Feb 13 01:32:02 UTC 2023

果然时区是UTC时区

  1. 查看一下docker中操作系统的版本,是ununtu 20.04
代码语言:shell复制
bash-4.4# cat /proc/version
Linux version 5.4.0-126-generic (buildd@lcy02-amd64-072) (gcc version 9.4.0 (Ubuntu 9.4.0-1ubuntu1~20.04.1)) #142-Ubuntu SMP Fri Aug 26 12:12:57 UTC 2022
  1. 再检查相应的docker的Dockerfile
代码语言:shell复制
FROM anapsix/alpine-java:8u202b08_jdk_unlimited

RUN mkdir -p /app/log 

WORKDIR /app

ADD ./abc.jar ./abc.jar

ENTRYPOINT ["/bin/sh", "-c", "java -jar abc.jar"]

解决问题

  1. 对Dockerfile进行修改,增加"时区配置"后如下:
代码语言:shell复制
FROM anapsix/alpine-java:8u202b08_jdk_unlimited

ENV TZ Asia/Shanghai
RUN ln -sf /usr/share/zoneinfo/${TZ} /etc/localtime
RUN echo ${TZ} > /etc/timezone

RUN mkdir -p /app/log 

WORKDIR /app

ADD ./abc.jar ./abc.jar

ENTRYPOINT ["/bin/sh", "-c", "java -jar abc.jar"]

发现还是不好使,时区还是原来的UTC时区!!!

  1. 检查后,发现原来缺少tzdata包

于是对Dockerfile进行修改,"安装tzdata包"后如下:

代码语言:shell复制
FROM anapsix/alpine-java:8u202b08_jdk_unlimited

RUN apk add --no-cache tzdata
ENV TZ Asia/Shanghai
RUN ln -sf /usr/share/zoneinfo/${TZ} /etc/localtime
RUN echo ${TZ} > /etc/timezone

RUN mkdir -p /app/log 

WORKDIR /app

ADD ./abc.jar ./abc.jar

ENTRYPOINT ["/bin/sh", "-c", "java -jar abc.jar"]
  1. 开始构建
代码语言:shell复制
sudo docker run --name cloud-render-oss-v3 -dit -p 8000:8000cloud-render-oss:v3
代码语言:shell复制
Step 1/13 : FROM anapsix/alpine-java:8u202b08_jdk_unlimited
 ---> 4357b436992a
Step 2/13 : MAINTAINER abc:1.0
 ---> Using cache
 ---> 7b43d961907c
Step 3/13 : RUN apk add --no-cache tzdata
 ---> Running in db41073e58ab
fetch http://dl-cdn.alpinelinux.org/alpine/v3.8/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.8/community/x86_64/APKINDEX.tar.gz
(1/1) Installing tzdata (2020a-r0)
Executing busybox-1.28.4-r3.trigger
OK: 25 MiB in 24 packages
Removing intermediate container db41073e58ab
 ---> e1cbf2ea9881
Step 4/13 : ENV TZ Asia/Shanghai
 ---> Running in d8689874d96d
Removing intermediate container d8689874d96d
 ---> b91855f5ae60
Step 5/13 : RUN echo ${TZ}
 ---> Running in e92b6f6aab22
Asia/Shanghai
Removing intermediate container e92b6f6aab22
 ---> 6eb50e8003f3
Step 6/13 : RUN ln -sf /usr/share/zoneinfo/${TZ} /etc/localtime
 ---> Running in 9bd7a1005cfd
Removing intermediate container 9bd7a1005cfd
 ---> 49270005a068
Step 7/13 : RUN echo ${TZ} > /etc/timezone
 ---> Running in fdccfb507a2c
Removing intermediate container fdccfb507a2c
 ---> d573b3b66e4f
  1. 再次进入容器,查看时间
代码语言:shell复制
bash-4.4# date
Mon Feb 13 09:50:49 CST 2023

大功告成!

0 人点赞