背景:
最近在寫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為東八區