解决 docker 容器时间与本地时间不一致

解决 docker 容器时间与本地时间不一致

第一种方法:启动时进行映射

运行 docker run 添加 -v /etc/localtime:/etc/localtime 选项,如下:
docker run -d -p 8080:80 -v /etc/localtime:/etc/localtime nginx
重点就是: -v /etc/localtime:/etc/localtime:ro

第二种:复制时区信息到容器

  • 如果本机时区正确直接:
docker cp /etc/localtime nginx:/etc/localtime
docker cp /etc/localtime [容器ID或名字]:/etc/localtime
  • 如果本机时区不正确:
docker cp /usr/share/zoneinfo/Asia/Shanghai nginx:/etc/localtime

自己习得心得

  • 进入容器
root@server105:~# docker exec -it Open_APIser /bin/bash
  • 查看容器内时间
root@4fc9ec0a5fae:/APIServer# date
Thu Feb  4 06:08:12 UTC 2021         # 关键字UTC
  • 查找关键字
root@4fc9ec0a5fae:/APIServer# find / -name UTC     
/usr/local/lib/python3.8/dist-packages/pytz/zoneinfo/Etc/UTC
/usr/local/lib/python3.8/dist-packages/pytz/zoneinfo/UTC
  • 复制路径查看目录下内容
root@4fc9ec0a5fae:/APIServer# ls /usr/local/lib/python3.8/dist-packages/pytz/zoneinfo/Etc/   
GMT    GMT+10  GMT+2  GMT+5  GMT+8  GMT-1   GMT-12  GMT-2  GMT-5  GMT-8  Greenwich  Universal
GMT+0  GMT+11  GMT+3  GMT+6  GMT+9  GMT-10  GMT-13  GMT-3  GMT-6  GMT-9  UCT        Zulu
GMT+1  GMT+12  GMT+4  GMT+7  GMT-0  GMT-11  GMT-14  GMT-4  GMT-7  GMT0   UTC
root@4fc9ec0a5fae:/APIServer# ls /usr/local/lib/python3.8/dist-packages/pytz/zoneinfo/     # 找到关键Asia(亚洲)
Africa      CET      Egypt    GMT+0      Iran       MST7MDT  Poland     UTC          zone.tab
America     CST6CDT  Eire     GMT-0      Israel     Mexico   Portugal   Universal    zone1970.tab
Antarctica  Canada   Etc      GMT0       Jamaica    NZ       ROC        W-SU
Arctic      Chile    Europe   Greenwich  Japan      NZ-CHAT  ROK        WET
Asia        Cuba     Factory  HST        Kwajalein  Navajo   Singapore  Zulu
Atlantic    EET      GB       Hongkong   Libya      PRC      Turkey     iso3166.tab
Australia   EST      GB-Eire  Iceland    MET        PST8PDT  UCT        leapseconds
Brazil      EST5EDT  GMT      Indian     MST        Pacific  US         tzdata.zi
  • 找到上海时区
root@4fc9ec0a5fae:/APIServer# ls /usr/local/lib/python3.8/dist-packages/pytz/zoneinfo/Asia/Shanghai 
  • 将上海时区文件创建软链接到/etc/目录下
root@4fc9ec0a5fae:/APIServer# ln -s /usr/local/lib/python3.8/dist-packages/pytz/zoneinfo/Asia/Shanghai /etc/localtime
  • 再次查看时间
root@4fc9ec0a5fae:/APIServer# date
Thu Feb  4 14:09:44 CST 2021        # 发现时间已经更新

启动时就指定参数

  • 启动命令中加参数
[root@localhost node_test]# docker run -itd --name test02 -e "TZ=Asia/Shanghai" node:latest
  • 查看结果
[root@localhost node_test]# docker exec -it test02  date
Tue Jun  8 11:45:53 CST 2021
原文地址:https://www.cnblogs.com/pengpengboshi/p/15237562.html