node debian 镜像 new Date 获取时间少 8 小时问题

问题

在 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈挨踢

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值