Docker addresses three solutions to the problem of inconsistency between container time and host time

  • 2020-05-30 21:24:07
  • OfStack

The Docker container time does not correspond to the host time

Check the time with the date command

View host time


[root@localhost ~]# date
2016 years  07 month  27 day   week 3 22:42:44 CST

View container time


root@b43340ecf5ef:/#date                                                                                                                          
Wed Jul 27 14:43:31 UTC 2016

As you can see, they were eight hours apart.

CST (China Shanghai Time, zone 8 time)
UTC (Coordinated Universal Time, standard time)

So, these two times should actually be 8 hours apart. (bluer: so no container has been set up, so the time difference between 1 and the host is 8h)

Therefore, the time zone must be aligned.

localtime for Shared hosts (method 1)

Specify startup parameters when creating the container, mount the localtime file into the container, and ensure that the time zone used by both is 1.


docker run --name <name> -v /etc/localtime:/etc/localtime:ro .... 

Copy localtime of the host (method 2)


docker cp /etc/localtime: The container ID or NAME 】 /etc/localtime

When you're done, check the current time through the date command.

However, the time of the application running in the container is not always updated, such as the MySQL service running in the container. After the update time, check the time of MySQL through sql


select now() from dual;

You can see that the time has not changed.

At this point, you must restart the mysql service or the Docker container so that mysql can read the time after the change.

Create a custom dockerfile (method 3)

The dockerfile file is created with nothing but a custom time format and time zone for the image.


FROM redis

FROM tomcat

ENV CATALINA_HOME /usr/local/tomcat

# Set the time zone 
RUN /bin/cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
  && echo 'Asia/Shanghai' >/etc/timezone \

Once saved, use the docker build command to generate the image for use.

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: