Docker设置时区

2023-04-26运维2 分钟189 次阅读
AI 摘要鱼粮不足,AI 今天先歇着 · 正文在下面

问题

前几天把项目部署到Docker中,今天查日志发现时间对不上,于是查看了当前容器时间

powershell 复制代码
docker exec -it demo bash # 进入到demo容器中
date # 查看当前容器时间

image.png
当前服务器时间

powershell 复制代码
date # 查看当前服务器时间

image.png
可见容器时间与宿主机之间相差了8小时

解决方案

1、docker run 添加参数

powershell 复制代码
# -v /etc/localtime:/etc/localtime


# 实例1
docker run -p 3306:3306 --name mysql -v /etc/localtime:/etc/localtime
 
# 实例2
docker run \
    --detach \
    --restart always \
    --name 'scribe' \
    --publish 11315:11315 \
    --mount type=bind,source=/data/gop/,destination=/data/gop/,consistency=consistent \
    -v /etc/localtime:/etc/localtime \

2、Dockerfile解决方案

powershell 复制代码
# 方法1
# 添加时区环境变量,亚洲,上海
ENV TimeZone=Asia/Shanghai
# 使用软连接,并且将时区配置覆盖/etc/timezone
RUN ln -snf /usr/share/zoneinfo/$TimeZone /etc/localtime && echo $TimeZone > /etc/timezone
 
# 方法2
# CentOS
RUN echo "Asia/shanghai" > /etc/timezone
# Ubuntu
RUN cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

3、docker-compose解决方案

powershell 复制代码
#第一种方式(推荐):
environment:
  TZ: Asia/Shanghai
  
#第二种方式:
environment:
  SET_CONTAINER_TIMEZONE=true
  CONTAINER_TIMEZONE=Asia/Shanghai
 
#第三种方式:
volumes:
  - /etc/timezone:/etc/timezone
  - /etc/localtime:/etc/localtime

4、宿主机直接执行命令给某个容器同步时间

powershell 复制代码
# 方法1:直接在宿主机操作
docker cp /etc/localtime 【容器ID或者NAME】:/etc/localtime
docker cp -L /usr/share/zoneinfo/Asia/Shanghai 【容器ID或者NAME】:/etc/localtime
 
# 方法2:登录容器同步时区timezone
ln -sf /usr/share/zoneinfo/Asia/Singapore /etc/localtime

在完成后,再通过date命令进行查看当前时间
但是,在容器中运行的程序的时间不一定能更新过来,比如在容器运行的mysql服务,在更新时间后,通过sql查看mysql的时间

sql 复制代码
select now() from dual;

可以发现,时间并没有更改过来
这时候必须要重启mysql服务或者重启docker容器,mysql才能读取到更改过后的时间

异常问题
Docker挂载/etc/timezone报错
问题现象
docker run 添加时间参数 -v /etc/timezone:/etc/timezone
或者
在docker-compose中挂载了
volumes:
-/etc/timezone:/etc/timezone
-/etc/localtime:/etc/localtime>

出现了报错信息

powershell 复制代码
ERROR: for mysql  Cannot start service mysql: OCI runtime create failed: 
 
container_linux.go:370: starting container process caused: process_linux.go:459:
 
 container init caused: rootfs_linux.go:59: mounting "/etc/timezone" to rootfs at "/var/lib/docker/overlay2/5f3d4c825cbbd4b0bb5359c97021e0bfd9ebff887057d6e9da427ebf5c4a3dd1/merged/etc/timezone" 
 
caused: not a directory: unknown: Are you trying to mount a directory onto a file (or vice-versa)? Check if the specified host path exists and is the expected type
 
ERROR: Encountered errors while bringing up the project.

问题解决

原因是centos7.6中/etc/timezone是一个文件夹,而不是一个文件

因此

执行如下命令:

powershell 复制代码
echo 'Asia/Shanghai' > /etc/timezone/timezone

然后

powershell 复制代码
docker run 添加时间参数 -v /etc/timezone/timezone:/etc/timezone

或者

在docker-compose中挂载了
volumes:
-/etc/timezone/timezone:/etc/timezone
-/etc/localtime:/etc/localtime

觉得有用就点个赞,不用登录也能读

评论

0 条
登录 之后才能评论
—
还没有评论,来说第一句