问题
在 node debian 镜像中,用 (new Date()).getHours()
与系统时间(东 8 区)少了 8 小时
系统时间
$ node
> (new Date()).getHours()
11
容器中的时间
$ node
> (new Date()).getHours()
3
原 Dockerfile
FROM node:20.5-bullseye
ARG proxy
RUN set -eux && \
sed -i -e 's#http://deb.debian.org#http://mirrors.aliyun.com#g' \
-e 's#http://security.debian.org#http://mirrors.aliyun.com#g' \
/etc/apt/sources.list && \
apt-get update && \
rm -rf /var/lib/apt/lists/
WORKDIR /app
COPY . .
RUN env http_proxy=$proxy https_proxy=$proxy npm install
ENTRYPOINT [ "node", "index.js" ]
原因
镜像运行起来容器未设置指定时区
解决
Dockerfile 中添加 ENV TZ='Asia/Shanghai'
及 apt-get install -yq tzdata
FROM node:20.5-bullseye
ARG proxy
# 设置时区
ENV TZ='Asia/Shanghai'
RUN set -eux && \
sed -i -e 's#http://deb.debian.org#http://mirrors.aliyun.com#g' \
-e 's#http://security.debian.org#http://mirrors.aliyun.com#g' \
/etc/apt/sources.list && \
apt-get update && \
# 安装 tzdata
apt-get install -yq tzdata && \
rm -rf /var/lib/apt/lists/
WORKDIR /app
COPY . .
RUN env http_proxy=$proxy https_proxy=$proxy npm install
ENTRYPOINT [ "node", "index.js" ]
验证
系统时间
$ node
> (new Date()).getHours()
11
容器中的时间
$ node
> (new Date()).getHours()
11
参考
- https://dev.to/0xbf/set-timezone-in-your-docker-image-d22
Set timezone in your docker image