How to make sure docker's time syncs with that of the host?
Asked Answered
M

22

137

I have dockers running on Linode servers. At times, I see that the time is not right on the dockers. Currently I have changed the run script in every docker to include the following lines of code.

yum install -y ntp
service ntpd stop
ntpdate pool.ntp.org

What I would ideally like to do however is that the docker should sync time with the host. Is there a way to do this?

Montemontefiascone answered 3/7, 2014 at 10:46 Comment(4)
possible duplicate of Will docker container auto sync time with the host machine?Leach
The container will use the same time as the host. See this Q&A with an answer from one of the Docker core developers.Leach
This is a definite duplicate question, but the answer to even the other question is talking about time zone which I am not really bothered about. The comment to the answer makes it clear that the clock drift does not occur as the docker and host use the same clock. Thanks Ben for pointing it out.Montemontefiascone
WARNING: there is some confusion about what a host is. On operating systems other than linux and Windows 10+ with linux subsystem, the docker machine (the host) is actually a virtual machine. When the docker host is not the same machine as the one you're running the docker commands on, you may see time skew, and things like mounting volumes won't work as you might expect. This also happens when you set up a remote docker machine, e.g. on DigitalOcean.Rafferty
M
134

The source for this answer is the comment to the answer at: Will docker container auto sync time with the host machine?

After looking at the answer, I realized that there is no way a clock drift will occur on the docker container. Docker uses the same clock as the host and the docker cannot change it. It means that doing an ntpdate inside the docker does not work.

The correct thing to do is to update the host time using ntpdate

As far as syncing timezones is concerned, -v /etc/localtime:/etc/localtime:ro works.

Montemontefiascone answered 4/7, 2014 at 6:39 Comment(9)
Tell me how that can be? If the docket uses the same clock as the system. how can the docker clock differ from the host. If a clock drift occurs, it will happen on the docker's host machine which is where clock drift needs fixing. I will be interested to know if I am wrong.Montemontefiascone
When using Docker on a Mac with boot2docker, the boot2docker VM may lose time. Docker remains in-sync with its host, but its host provides the wrong time. Rebooting the VM is the simplest fix for this.Pyne
That is a totally different issue where the VM looses its time. Technically, docker is still in sync with its host which is the VM.Montemontefiascone
@Nathaniel Can you please tell me how you reboot the VM? I'm experiencing a timezone problem - I'm using a Mac and Oracle's VM Virtualbox Manager. At the moment I have InfluxDB in a docker and the timezone is not UTC, so all my data in the db is of yesterday although collected today -_-Usurious
@ISJ: boot2docker restart Or if you run your own VM you can ntpdate there.Pyne
see github.com/boot2docker/boot2docker/pull/661 for a purported fix/mitigationQuicktempered
I'm sill having this issue without boot2docker VM (Docker for Mac 1.12), even after restarting the container and Docker itself.Hallowed
I'm on Windows. Host machine time is 15:06, container time is 18:41... wtfTroublemaker
For those still confused (@willem), this answer assumes that the docker host is the same machine that the docker command is running on, which is often not the case. See my comment for more info.Rafferty
S
69

You can add your local files (/etc/timezone and /etc/localtime) as volume in your Docker container.

Update your docker-compose.yml with the following lines.

volumes:
    - "/etc/timezone:/etc/timezone:ro"
    - "/etc/localtime:/etc/localtime:ro"

Now the container time is the same as on your host.

Schreib answered 8/6, 2017 at 16:1 Comment(0)
M
52

This will reset the time in the docker server:

docker run --rm --privileged alpine hwclock -s

Next time you create a container the clock should be correct.

Source: https://github.com/docker/for-mac/issues/2076#issuecomment-353749995

Meredith answered 19/3, 2019 at 16:38 Comment(8)
Now that's the secret I was looking for! Was off by days and certs were grumpy. Thank you!Prolonge
Thanks for this. Worked like a charm.Atonality
how to use it with docker-compose ?Nardi
I was seeing the much-reported Docker for Windows not time synching after sleeping bug, this fix worked like magic! What is it doing?Oregon
AWESOME, fixed my issue in Docker / Win10Footslog
Proper fix for WSL 2 time shift after sleep: #60959774Petra
This is exactly what I needed, spent an hour trying all the different ntpdate solutions but Docker blocks it. This worked for me with my .devcontainerJablon
That is the wayTwilley
D
40

If you are using boot2docker and ntp doesn't work inside the docker VM (you are behind a proxy which does not forward ntp packets) but your host is time-synced, you can run the following from your host:

docker-machine ssh default "sudo date -u $(date -u +%m%d%H%M%Y)"

This way you are sending your machine's current time (in UTC timezone) as a string to set the docker VM time using date (again in UTC timezone).

NOTE: in Windows, inside a bash shell (from the msys git), use:

docker-machine.exe ssh default "sudo date -u $(date -u +%m%d%H%M%Y)"
Demarcate answered 3/9, 2015 at 7:35 Comment(3)
Perfect! That was exactly my problem and it fixes it instantly without needing to reboot docker-machine.Hume
Is it possible to set the seconds? I tried adding %S but I get invalid timeAbrahan
@Sakib, the date command is only accepts the format MMDDhhmm[[CC]YY][.ss] to set the date, so to add seconds, you need to put them at the end of the string like this: +%m%d%H%M%Y.%S.Demarcate
M
31

This is what worked for me with a Fedora 20 host. I ran a container using:

docker run -v /etc/localtime:/etc/localtime:ro -i -t mattdm/fedora /bin/bash

Initially /etc/localtime was a soft link to /usr/share/zoneinfo/Asia/Kolkata which Indian Standard Time. Executing date inside the container showed me same time as that on the host. I exited from the shell and stopped the container using docker stop <container-id>.

Next, I removed this file and made it link to /usr/share/zoneinfo/Singapore for testing purpose. Host time was set to Singapore time zone. And then did docker start <container-id>. Then accessed its shell again using nsenter and found that time was now set to Singapore time zone.

docker start <container-id>
docker inspect -f {{.State.Pid}} <container-id>
nsenter -m -u -i -n -p -t <PID> /bin/bash

So the key here is to use -v /etc/localtime:/etc/localtime:ro when you run the container first time. I found it on this link.

Hope it helps.

Monostome answered 3/7, 2014 at 14:57 Comment(1)
this worked for me on a CentOS Linux release 7.6.1810Walli
C
17

This easy solution fixed our time sync issue for the docker kernel in WSL2.

Open up PowerShell in Windows and run this command to resync the clock.

wsl -d docker-desktop -e /sbin/hwclock -s

You can then test it using

docker run -it alpine date

Reference: https://github.com/docker/for-win/issues/10347#issuecomment-776580765

Chondrite answered 29/9, 2021 at 10:49 Comment(2)
I'm running on Windows with WSL; and this this fixed the time in my running container, and while it was running too.Latarsha
on WIndows 11 this didnt worked, Docker Engine v20, using Docker Compose v2Cask
H
13

docker-compose form:

Add /etc/localtime:/etc/localtime:ro to the volumes attribute:

version: '3'

services:
  a-service:
      image: service-name
      container_name: container-name
      volumes:
        - /etc/localtime:/etc/localtime:ro
Hedvige answered 21/8, 2018 at 5:46 Comment(2)
What does it mean :ro?Dogtrot
@AldoInáciodaSilva means read-onlyHedvige
C
12

I have the following in the compose file

volumes:
  - "/etc/timezone:/etc/timezone:ro"
  - "/etc/localtime:/etc/localtime:ro"

Then all good in Gerrit docker with its replication_log set with correct timestamp.

Cootch answered 7/12, 2017 at 10:1 Comment(3)
I have Debian (9) containers in CentOS (7) host, and mounting localtime works, but timezone cannot, because on host it's directory while in container it's file.Cherrylchersonese
What does it mean :ro at the end?Dogtrot
:ro = read onlyCootch
H
11

If you're using docker-machine, the virtual machines can drift. To update the clock on the virtual machine without restarting run:

docker-machine ssh <machine-name|default>
sudo ntpclient -s -h pool.ntp.org

This will update the clock on the virtual machine using NTP and then all the containers launched will have the correct date.

Handgun answered 18/7, 2016 at 15:9 Comment(2)
The command worked and it updated the time. However, the time started drifting again and I had to run the command again. How to make it sync automatically inside the docker host?Chandrachandragupta
for me, I needed to restart docker-machine - docker-machine restart then eval "$(docker-machine env default)" and that fixed the time difference.Chong
V
11

I was facing a time offset of -1hour and 4min

Restarting Docker itself fixed the issue for me.

To set the timezone in general:

  1. ssh into your container: docker exec -it my_website_name bash

  2. run dpkg-reconfigure tzdata

  3. run date
Venn answered 22/11, 2017 at 17:52 Comment(1)
This worked for me from the console on macOS High Sierra 10.13.6 (17G65) using docker-compose: docker-compose exec <servicename> bundle exec dpkg-reconfigure tzdataCincinnati
I
9

It appears there can by time drift if you're using Docker Machine, as this response suggests: https://mcmap.net/q/168375/-will-a-docker-container-auto-sync-time-with-its-host-machine , due to VirtualBox.

Quick and easy fix is to just restart your VM:

docker-machine restart default
Idiophone answered 1/4, 2016 at 3:1 Comment(1)
in docker windows was no default machine, i restarted the daemon over the reset tab in the docker config program shipped with docker windows, after that the time was okBehavior
U
7

Windows users:

The solution is very simple. Simply open a powershell prompt and enter:

docker run --privileged --rm alpine date -s "$(Get-Date ([datetime]::UtcNow) -UFormat "+%Y-%m-%d %H:%M:%S")"

To check that it works, run the command:

docker run --rm -it alpine date


My solution is inspired by something I found in docker forum thread. Anyways, it was the only solution that worked for me on docker desktop, except for restarting my machine (which also works). Here's a link to the original thread: https://forums.docker.com/t/syncing-clock-with-host/10432/23

The difference between the thread answer and mine is that mine converts the time to UTC time, which is necessary for e.g. AWS. Otherwise, the original answer from the forum looks like this:

docker run --privileged --rm alpine date -s "$(date -u "+%Y-%m-%d %H:%M:%S")"

Unconformable answered 8/12, 2020 at 17:17 Comment(1)
It might be worth noting that alpine can be substituted with the image you are having trouble with, and also, for my situation, I had to add --user=root to my command to make it work. This solved it for me though. So thanks!Lacrosse
A
6

For docker on macOS, you can use docker-time-sync-agent. It works for me.

Acuff answered 13/3, 2017 at 8:39 Comment(2)
Apparently this is fixed now github.com/docker/for-mac/issues/17Itemized
Time out of sync still happen on docker version 18.03.1-ce-mac65, and this solution fixes it.Cramfull
N
5

With docker for windows I had to tick

MobyLinuxVM > Settings > Integration Services > Time synchronization 

in Hyper-V manager and it worked

Nic answered 21/1, 2017 at 0:55 Comment(3)
There's one problem though. It seems that after you restart the host the setting is untickedFlotilla
Yes - this seems to happen on some windows builds (see github.com/docker/for-win/issues/409)Nic
In my case, that checkbox is already checked, but the container time is three days behind the host time.Unstressed
T
3

Although this is not a general solution for every host, someone may find it useful. If you know where you are based (UK for me) then look at tianon's answer here.

FROM alpine:3.6
RUN apk add --no-cache tzdata
ENV TZ Europe/London

This is what I added to my Dockerfile ^ and the timezone problem was fixed.

Trout answered 25/7, 2019 at 12:36 Comment(0)
G
2

Docker Usage

Here's a complete example which builds a docker image for a go app in a multistage build. It shows how to include the timezone in your image.

FROM golang:latest as builder

WORKDIR /app

ENV GO111MODULE=on \
    CGO_ENABLED=0 \
    GOOS=linux \
    GOARCH=amd64

COPY go.mod .
COPY go.sum .

RUN go mod download

COPY . .

RUN go build -a -installsuffix cgo -ldflags '-extldflags "-static"' -o main

### Certs
FROM alpine:latest as locals

RUN apk --update --no-cache add ca-certificates

RUN apk add --no-cache tzdata

### App
FROM scratch 

WORKDIR /root/

COPY --from=locals /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt

COPY --from=builder app/main .

COPY --from=builder app/templates ./templates

COPY --from=locals /usr/share/zoneinfo /usr/share/zoneinfo

ENV TZ=Asia/Singapore

EXPOSE 8000

CMD ["./main"]
Gunlock answered 19/8, 2020 at 6:14 Comment(0)
L
2

For me, restarting Docker Desktop did not help. Shutting down Win10 and start it again, it did help.

Limitation answered 25/11, 2020 at 13:12 Comment(0)
A
2

I saw this on windows, launching Prometheus from docker-compose. I had a 15 hour time drift.

If you are running Docker Desktop on WSL, you can try running wsl --shutdown from a powershell prompt. Docker Desktop should restart, and you can try running your docker container again.

Worked for me, and I didn't have to restart.

Andrel answered 24/3, 2021 at 14:8 Comment(1)
this was the right answer to my problem. my machine was already perfectly synced with worldclocks but my docker container had about 50 seconds difference. the wsl --shutdown helped to force docker to pickup the right time.Reichstag
B
1

I've discovered that if your computer goes to sleep then the docker container goes out of sync.

https://forums.docker.com/t/time-in-container-is-out-of-sync/16566

I have made a post about it here Certificate always expires 5 days ago in Docker

Billiards answered 31/3, 2020 at 21:52 Comment(0)
H
0

Enabling Hyper-V in Windows Features solved the problem: Windows Features

Harday answered 19/11, 2020 at 9:14 Comment(0)
T
0

For whatever reason none of these answers solved my problem.

It had nothing to do with the docker date/time for the images I was creating. It had to do with my local WSL date time.

Once I ran sudo ntpdate-debian everything worked.

If you don't have ntp just install it and run the command. If you aren't using debian then you probably won't have the shell script ntpdate-debian, but you can use ntpd -gq as well. Basically just update the date for your main WSL distro.

Torquay answered 8/2, 2021 at 16:39 Comment(0)
R
0

This code worked for me

docker run -e TZ="$(cat /etc/timezone)" myimage
Rech answered 13/12, 2022 at 12:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.