我在Linode服务器上运行着Docker。有时候,我发现Docker上的时间不正确。目前,我已经在每个Docker的运行脚本中添加了以下代码行。
yum install -y ntp
service ntpd stop
ntpdate pool.ntp.org
然而,我最理想的情况是Docker应该与主机同步时间。是否有一种方法可以实现这一点?
ntpdate
无效。ntpdate
更新主机时间。-v /etc/localtime:/ etc/localtime:ro
可以工作。boot2docker
,请执行boot2docker restart
来重启虚拟机。如果您在运行自己的虚拟机,则可以在其中执行ntpdate
命令来同步时间。 - Nathaniel Waisbrot您可以将本地文件(/etc/timezone和/etc/localtime)作为卷添加到Docker容器中。
使用以下行更新您的docker-compose.yml
文件。
volumes:
- "/etc/timezone:/etc/timezone:ro"
- "/etc/localtime:/etc/localtime:ro"
现在容器时间与您的主机时间相同。
这将重置docker服务器中的时间:
docker run --rm --privileged alpine hwclock -s
下次您创建容器时,时钟应该是正确的。
来源:https://github.com/docker/for-mac/issues/2076#issuecomment-353749995
docker-machine ssh default "sudo date -u $(date -u +%m%d%H%M%Y)"
这样做会将您机器当前的时间(在UTC时区)作为字符串发送,使用date
设置docker虚拟机的时间(同样在UTC时区)。
注意:在Windows中,在msys git的bash shell内使用:
docker-machine.exe ssh default "sudo date -u $(date -u +%m%d%H%M%Y)"
date
命令只接受格式为MMDDhhmm[[CC]YY][.ss]
的日期设置方式,因此要添加秒数,您需要将它们放在字符串的末尾,如下所示:+%m%d%H%M%Y.%S
。 - gvlx以下是我在Fedora 20主机上使用的方法。我运行了一个容器:
docker run -v /etc/localtime:/etc/localtime:ro -i -t mattdm/fedora /bin/bash
最初,/etc/localtime
是一个软链接,指向印度标准时间 /usr/share/zoneinfo/Asia/Kolkata
。在容器内执行 date
命令,显示的时间与主机上相同。我退出了 shell 并停止了容器,使用命令 docker stop <container-id>
。
接下来,我删除了这个文件,并将其链接到测试目的地新加坡时区 /usr/share/zoneinfo/Singapore
。主机时间已设置为新加坡时区。然后运行命令 docker start <container-id>
。再次使用 nsenter
访问其 shell,发现时间现在已设置为新加坡时区。
docker start <container-id>
docker inspect -f {{.State.Pid}} <container-id>
nsenter -m -u -i -n -p -t <PID> /bin/bash
-v /etc/localtime:/etc/localtime:ro
。我在这个链接上找到了它。
希望能对你有所帮助。这个简单的解决方案修复了我们在WSL2中使用docker内核的时间同步问题。
在Windows中打开PowerShell,运行以下命令以重新同步时钟。
wsl -d docker-desktop -e /sbin/hwclock -s
您可以使用以下方式进行测试:
docker run -it alpine date
参考文献:https://github.com/docker/for-win/issues/10347#issuecomment-776580765
我在compose文件中有以下内容
volumes:
- "/etc/timezone:/etc/timezone:ro"
- "/etc/localtime:/etc/localtime:ro"
然后在 Gerrit Docker 中,其 replication_log 设置正确的时间戳后一切良好。
在 volumes
属性中添加 /etc/localtime:/etc/localtime:ro
:
version: '3'
services:
a-service:
image: service-name
container_name: container-name
volumes:
- /etc/localtime:/etc/localtime:ro
如果您正在使用docker-machine,虚拟机可能会漂移。要在不重启虚拟机的情况下更新虚拟机上的时钟,请运行:
docker-machine ssh <machine-name|default>
sudo ntpclient -s -h pool.ntp.org
这将使用NTP更新虚拟机上的时钟,然后启动的所有容器都将具有正确的日期。
docker-machine restart
,然后运行eval "$(docker-machine env default)"
以解决时间差的问题。 - Silas Palmer我遇到了一个时间偏移量为-1小时4分钟的问题。
重新启动Docker解决了我的问题。
设置时区的方法如下:
通过ssh进入你的容器:
docker exec -it my_website_name bash
运行dpkg-reconfigure tzdata
date
docker-compose exec <servicename> bundle exec dpkg-reconfigure tzdata
。 - Zack Morris
docker
命令的机器时,您可能会看到时间偏差,并且像挂载卷这样的事情可能无法按照您的预期工作。当您设置远程Docker机器时,例如在DigitalOcean上,也会发生这种情况。 - Codebling