解决Docker容器内时区不一致问题

1、Dockerfile中创建时区文件

CentOS

FROM centos
ENV TZ=Asia/Shanghai
RUN rm -f /etc/localtime \
&& ln -sv /usr/share/zoneinfo/${TZ} /etc/localtime \
&& echo "${TZ}" > /etc/timezone

Alpine

FROM alpine
ENV TZ=Asia/Shanghai
RUN apk add --no-cache tzdata \
	&& echo "${TZ}" > /etc/timezone \
	&& ln -sf /usr/share/zoneinfo/${TZ} /etc/localtime \
	&& apk del tzdata \
	# 可选,上面已指定no-cache
	&& rm -rf /var/cache/apk/*

ubuntu

FROM ubuntu
ENV TZ=Asia/Shanghai 
RUN echo "${TZ}" > /etc/timezone \ 
    && ln -sf /usr/share/zoneinfo/${TZ} /etc/localtime \ 
    && apt-get update \ 
    && apt-get install -y tzdata \ 
    && rm -rf /var/lib/apt/lists/*

2、运行容器时挂载主机时区

方式1

挂载本地 /etc/localtime 到容器内:

docker run -it -v /etc/localtime:/etc/localtime centos /bin/sh

方式2

挂载本地 /usr/share/zoneinfo/Asia/Shanghai 到容器内

docker run -it -v /usr/share/zoneinfo/Asia/Shanghai:/etc/localtime centos /bin/sh
posted @ 2023-02-20 14:23  gaozejie  阅读(303)  评论(0编辑  收藏  举报