Docker container and host time synchronization

Preface

After the Docker container is created, you may find that the container time is inconsistent with the host time. In this case, you need to synchronize their times to make the container time consistent with the host time.

1. Analyze the reasons for time inconsistency

The host uses the CST time zone, and CST should refer to (China Shanghai Time, East Eighth District Time)
The container uses the UTC time zone, and UTC should refer to (Coordinated Universal Time, Standard time)
At this time, the time zones used between the container and the host are inconsistent, and the two time zones are 8 hours apart.

2. Method of synchronizing time

Option 1: Shared hosting localtime

Specify the startup parameters when creating the container, and mount the host's localtime file into the container to ensure that the time zones of the host and the container are consistent.
docker run --volume /etc/localtime:/etc/localtime:ro <image_name>

docker run -p 3306:3306 --name mysql \
-v /mydata/mysql/log:/var/log/mysql \
-v /mydata/mysql/data:/var/lib/mysql \
-v /mydata/mysql/conf:/etc/mysql \ 
-v /etc/localtime:/etc/localtime:ro \
-e MYSQL_ROOT_PASSWORD=root \
-d mysql:5.7

Option 2: Copy the host localtime to the container

1. Check the host time and docker container time:

//查看容器id
docker ps
//检查时间使用:date
date
//进入容器:
 docker exec -it  {
    
    容器名称或者容器id}  /bin/bash
 //查看时间
 date

2. Enter the docker container to create the folder with the copy time

//进入容器:
 docker exec -it  {
    
    容器名称或者容器id}  /bin/bash
 //创建文件夹
 mkdir -p /usr/share/zoneinfo/Asia
 mkdir -p /usr/share/zoneinfo/Pacific
 //退出
 exit;

3. Copy files from the host to the docker container

docker cp /etc/localtime {
    
    容器id}:/etc/localtime
docker cp -L /usr/share/zoneinfo/Asia/Shanghai {
    
    容器id}:/etc/localtime

4. Enter the docker container to check the time

//进入容器:
 docker exec -it  {
    
    容器名称或者容器id}  /bin/bash
 //查看时间
 date

Option 3: Customize the time format and time zone of the image when creating the dockerfile

Add a line of content in the early stage of dockerfile creation, which specifies the time format and time zone of the image.

#Set time zone

RUN /bin/cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone

Summary: Through the above three solutions, the time of the docker container and the host time can be synchronized. Which solution to choose depends on the actual situation.

I used the second one here
Insert image description here

Guess you like

Origin blog.csdn.net/qq_44696532/article/details/134600126