背景:
最近在写golang相关代码。其中用到了时间操作的相关函数,如下:
nowTime := time.Now() nUnixEndTime := nowTime.Unix() nHour, nMin, nSec := nowTime.Clock()
但代码跑在docker容器中,时间就取不对了。原因为容器中的时区与本机时区不一致。
处理:
设置docker容器的时区,Dockerfile如下设置:
FROM alpine LABEL license='SPDX-License-Identifier: Apache-2.0' copyright='Copyright (c) 2018' # The main mirrors are giving us timeout issues on builds periodically. # So we can try these. ENV TZ=Asia/Shanghai # RUN sed -e 's/dl-cdn[.]alpinelinux.org/nl.alpinelinux.org/g' -i~ /etc/apk/repositories RUN echo "http://mirrors.aliyun.com/alpine/v3.4/main/" > /etc/apk/repositories && apk --no-cache add tzdata zeromq && ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo '$TZ' > /etc/timezone
ps:
因alpine镜像中并没有时区相关的包,需要下载安装才行。并设置localtime和timezone为东八区