1、问题说明:
运行容器时,经常发现容器时间和宿主机时间相差八个小时,如下所示:
[root@Server1 ~]# date
Sun Feb 16 14:26:50 CST 2020
[root@Server1 ~]# ls -l /etc/localtime
lrwxrwxrwx 1 root root 33 Feb 15 09:32 /etc/localtime -> /usr/share/zoneinfo/Asia/Shanghai
[root@Server1 ~]# docker exec -it redis-test date
Sun Feb 16 06:27:04 UTC 2020
[root@Server1 ~]# docker exec -it redis-test ls -l /etc/localtime
lrwxrwxrwx 1 root root 27 Jan 30 00:00 /etc/localtime -> /usr/share/zoneinfo/Etc/UTC
可以看出区别是,宿主机的时区是CST,CST是 China Shanghai Time,东八区时间;而容器时区是UTC,指 Coordinated Universal Time,标准时间。
2、解决方法
方法1:把宿主机的localtime覆盖到容器
[root@Server1 ~]# docker cp /etc/localtime redis-test:/etc/localtime
[root@Server1 ~]# docker exec -it redis-test date
Sun Feb 16 14:29:58 CST 2020
[root@Server1 ~]# date
Sun Feb 16 14:30:02 CST 2020
方法2:运行容器时指定时区
[root@Server1 ~]# docker run --name redis-test -d -e "TZ=Asia/Shanghai" redis
1a40155f67758554fc2621ef60f4ecb3e251f35c1c1ed1587a4ffed7c48acdfd
[root@Server1 ~]# docker exec -it redis-test date
Sun Feb 16 14:33:57 CST 2020
重启容器后,时间仍然和宿主机是同步的
[root@Server1 ~]# docker restart redis-test
redis-test
[root@Server1 ~]# docker exec -it redis-test date
Sun Feb 16 14:35:36 CST 2020
[root@Server1 ~]# date
Sun Feb 16 14:35:37 CST 2020