1. Docker container time is inconsistent with the host
If localtime is not configured separately during the startup of the Docker container, it is likely that the Docker container time is inconsistent with the host time. For example, the difference between UTC and CST is 8 hours. In other words, the container time is 8 hours different from Beijing time.
Problem description
Question: The container time is 8 hours apart from Beijing time
# Check host time[root@localhost ~]# date 2020Year07moon27day Wednesday 22:42:44 CST # Check container time# docker exec -it <containerid> /bin/sh root@b43340ecf5ef:/# date Wed Jul 27 14:43:31 UTC 2020
Reason: The host has a time zone set, but the Docker container is not set, resulting in an 8-hour difference between the two.
- CST should refer to (China Shanghai Time, East Eighth District Time)
- UTC should refer to (Coordinated Universal Time, Standard Time)
So, these two times should actually be 8 hours apart
Therefore, the time zones of both must be unified
Solution
Method 1: When initializing the container, the container time is synchronized with the host, docker run adds time parameters
docker run -itd --privileged=true -v /etc/localtime:/etc/localtime:ro #Exampledocker run -itd \ -e MYSQL_ROOT_PASSWORD=123456 \ -v /home/mysql/data:/var/lib/mysql \ -v /home/mysql/log:/var/log/mysql \ -v /home/mysql/etc/:/etc/mysql// \ -v /etc/localtime:/etc/localtime:ro \ --name mysql-server \ --network host \ --restart=always \ --privileged=true \ mysql:5.7.37
Method 2: Dockerfile solution
# Method 1# Add time zone environment variables, Asia, ShanghaiENV TimeZone=Asia/Shanghai # Use soft connection and overwrite time zone configuration /etc/timezoneRUN ln -snf /usr/share/zoneinfo/$TimeZone /etc/localtime && echo $TimeZone > /etc/timezone # Method 2# CentOS RUN echo "Asia/shanghai" > /etc/timezone # Ubuntu RUN cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
Method 3: docker-compose solution
#The first method (recommended):environment: TZ: Asia/Shanghai #The second method:environment: SET_CONTAINER_TIMEZONE=true CONTAINER_TIMEZONE=Asia/Shanghai #The third method:volumes: - /etc/timezone:/etc/timezone - /etc/localtime:/etc/localtime
Method 4: The running container can directly execute commands to give a container synchronization time.
#Method 1 Operation directly on the hostdocker cp /etc/localtime 【containerIDorNAME】:/etc/localtime docker cp -L /usr/share/zoneinfo/Asia/Shanghai 【containerIDorNAME】:/etc/localtime #Method 2 Log in to the container to synchronize the timezone timezone, usually due to different time zones, time differenceln -sf /usr/share/zoneinfo/Asia/Singapore /etc/localtime
After completion, check the current time through the date command
However, the time of the program running in the container may not be updated. For example, after the update time, check the time of mysql through sql through sql.
select now() from dual;
It can be found that the time has not changed
At this time, you must restart the mysql service or restart the docker container. Mysql can read the time after the change
2. Host time is not synchronized
ntp time server-time synchronization
Two specific modes:
1. The number of servers is relatively small, and it can be synchronized directly with the time server.
2. There are many local servers, and you can build your own time synchronization server locally
Two commands for time synchronization:
-
ntpd
: Calibration time, calibrate time bit by bit, and finally slowly correct the time. The ntpd service can correct the CPU tick while correcting the time. ntpd has a self-protection setting: If the time difference between the local machine and the source is too large, ntpd will not run -
ntpdate
: Will not consider whether other programs will cause pain, and directly adjust the time, which may affect the program
ntpdate [-nv] [ IP/hostname] # ntpdate -u 192.168.0.2 # ntpdate -u # ntpdate -u >>/var/log/ 2>&1;hwclock -w
Note: -u: Specify using an unprivileged port to send data packets, which can be synchronized with the host through the firewall. This parameter is available or not, it depends on yourself.
The ideal approach is:
Use ntpd to calibrate the clock, rather than adjusting the time on the computer clock.
When the computer has just started but has not started many services, you can use ntpdate to synchronize the time
Directly use commands to synchronize with the time server
Example: Synchronize using ntpdate:
ntpdate -u #Here you can be a public time serverIPaddress,It can also be the following two built by usntp服务器address
#Public time server IP address#Ali Cloud Time Server #centos also has several time servers (it's better to use domestic ones)
You can add a scheduled schedule and synchronize it regularly
Note: When there is time synchronization server, use this command directly to enable the host to achieve time synchronization.
crontab -e */1 * * * * /usr/sbin/ntpdate -u > /dev/null 2&1
Built a self-built ntpd time synchronization server
NTPCommunication protocol principle: First, the host startsNTP。 The client willNTPThe server sends the adjustment timemessage。 ThenNTP serverThe current standard time will be sent toclient clientAccepted fromserverAfter the time,Will adjust your time based on this information。This enables network timing。 #NTP Demon uses UDP 123 portThe level of the remote server(stratum): becauseNTPIt is a layered structure,Top server,Multi-layerRelay ServerGo to the client. Therefore, the server can be set from high to low level1-16. To reduce load and network blockage,In principle, it should be avoided to connect directly to the level of1The server of
1. Configure the ntp server
1) Installation
# yum -y install ntp
2) Start up automatically
# systemctl start ntpd # systemctl enable ntpd
3) Modify the configuration file: (Detailed explanation)
[root@localhost ~]# less /etc/ # For more information about this file, see the man pages # (5), ntp_acc(5), ntp_auth(5), ntp_clock(5), ntp_misc(5), ntp_mon(5). driftfile /var/lib/ntp/drift #Difference record between system time and BIOS event Configure machine permissions synchronized with the machine↓ # Permit time synchronization with our time source, but do not # permit the source to query or modify the service on this system. restrict default kod nomodify notrap nopeer noquery restrict -6 default kod nomodify notrap nopeer noquery
Any operation is rejected by default. Any IP4 address and IP6 address cannot be modified, trap remote login, cannot try peering, cannot proofread the time,
restrict Controls relevant permissions.
The syntax is: restrict [ ClientIP ] mask [ IPMask ] [parameter]
The IP address can also be default, default refers to all IPs
The parameters are as follows:
-
nomodify
: The client cannot change the time parameters of the server, but the client can perform network timing verification through the server. -
notrust
: Reject no authenticated user -
noquery
: The client cannot use ntpq and ntpc to query the ntp server, which is equivalent to not providing proofreading time service. -
notrap
: The trap remote login function is not provided. The trap service is a remote time log service. The mode is refused to be provided for matching hosts. 6 Control message trap service. Trap service is a subsystem of the ntpdq control message protocol used for remote event logging programs. -
nopeer
: Used to prevent hosts from trying to peer with servers -
kod
: Send KoD packets when access violations are made, and send Kiss-Of-Death messages to unsafe visitors. restrict -6 indicates the permission settings of IPV6 addresses.
How to control customer scope # Permit all access over the loopback interface. This could #The following configuration allows any permissions to run on the local interface,# be tightened as well, but to do so would effect some of #It is best to tighten permissions here, but it will affect some management functions# the administrative functions. restrict 127.0.0.1 restrict ::1 # Hosts on local network are less restricted. #Configuration Configure smaller permissions to the local LAN#restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap Native synchronization options with public time server set upNTPHost source(inpreferRepresentative host) # Use public servers from the project.# Please consider joining the pool (/). Please consider joining the pool projectserver iburst server iburst server iburst server iburst
server host [ key n ] [ version n ] [ prefer ] [ mode n ] [ minpoll n ] [ maxpoll n ] [ iburst ] inhostIt's the upper levelNTPServer'sIPAddress or domain name,The following parameters are explained as follows: ◆ key: 表示所有发往Server's报文包含有秘钥加密of认证信息,nyes32integer of bits,Indicates the key number。 ◆ version: 表示发往上层Server's报文使用of版本号,n默认yes3,可以yes1or2。 ◆ prefer: Priority use。 ◆ mode: Specify data packetsmodeThe value of the field。 ◆ minpoll: 指定与查询该Server's最小The time interval is2ofnPower seconds,nDefault is6,The range is4-14。 ◆ maxpoll: 指定与查询该Server's最大The time interval is2ofnPower seconds,nDefault is10,The range is4-14。 ◆ iburst: When initial synchronization request,Send bursts one after another8A message,The time interval is2Second。
#broadcast 192.168.1.255 autokey # broadcast server #broadcastclient # broadcast client #broadcast 224.0.1.1 autokey # multicast server #multicastclient 224.0.1.1 # multicast client #manycastserver 239.255.254.254 # manycast server #manycastclient 239.255.254.254 autokey # manycast client When external time is not available,Local(This machine)Time as service time,Local time 127.127.1.0 express Level is10 # Undisciplined Local Clock. This is a fake driver intended for backup # and when no outside source of synchronized time is available. #server 127.127.1.0 # local clock #fudge 127.127.1.0 stratum 10 Here are some encryption authentication configurations # Enable public key cryptography. #crypto includefile /etc/ntp/crypto/pw # Key file containing the keys and key identifiers used when operating # with symmetric key cryptography. keys /etc/ntp/keys # Specify the key identifiers which are trusted. #trustedkey 4 8 42 # Specify the key identifier to use with the ntpdc utility. #requestkey 8 # Specify the key identifier to use with the ntpq utility. #controlkey 8 # Enable writing of statistics records. #statistics clockstats cryptostats loopstats peerstats
A simple example is as follows:
restrict default kod nomodify notrap nopeer noquery #Denied all IP4 requests# restrict -6 default kod nomodify notrap nopeer noquery #Settings for ipv6 # Allow all local operationsrestrict 127.0.0.1 #restrict -6 ::1 # Allowed LAN segments or separate ips for certain permissionsrestrict 10.0.0.0 mask 255.0.0.0 nomodify motrap restrict 192.168.0.0 mask 255.255.255.0 nomodify motrap restrict 192.168.1.123 mask 255.255.255.255 nomodify motrap # Use the upper-level Internet ntp serverrestrict restrict restrict restrict server prefer server server server # If you cannot communicate with the upper ntp server, local time is the standard timeserver 127.127.1.0 # local clock fudge 127.127.1.0 stratum 10 driftfile /var/lib/ntp/drift # Calculate the frequency error between this ntp server and the upper ntpserver # Key file containing the keys and key identifiers used when operating # with symmetric key cryptography. keys /etc/ntp/keys logfile /var/log/ #Log files
Configure /etc/sysconfig/ntpd file
ntp service, by default, only synchronizes system time. If you want ntp to synchronize hardware time at the same time, you can set the /etc/sysconfig/ntpd file, and add SYNC_HWCLOCK=yes to the /etc/sysconfig/ntpd file, so that the hardware time can be synchronized with the system time.
# Allow BIOS to be synchronized with the system time, or through the hwclock -w command
# vim /etc/sysconfig/ntpd # Add toSYNC_HWCLOCK=yes
4) Start the ntpd service
# systemctl start ntpd
Check the port of ntp and you can see port 123
# netstat -unlnp
Check whether the ntp server has connections with the upper layer
# ntpstat synchronised to NTP server (84.16.73.33) at stratum 2 time correct to within 184 ms polling server every 128 s
When it first started, it is usually:
# ntpstat unsynchronised time server re-starting polling server every 64 s
ntptrace -n 127.0.0.1 127.0.0.1: stratum 3, offset -0.001095, synch distance 0.532610 116.193.83.174: timed out, nothing received
Check the status of ntp server and upper ntp server: ntpq
# ntpq -p # in: # remote - the IP or host name of the native and upper ntp, "+" has a connection to be used as a candidate, and "*" is being used # refid - ntp address to go up to the next level #st - stratum level # when - How many seconds have I ever synchronized the time# poll - How many seconds will the next update be# reach - the number of times that have been requested to the upper ntp server# delay - Network delay# offset - Time compensation# jitter - System time difference between bios # ntpq -p remote refid st t when poll reach delay offset jitter ============================================================================== * 10.137.38.86 2 u 111 128 377 27.480 -5.995 1.852
2. Configure the NTP client
On all clients vim /etc/, add:
server # Configured for the aboventpServer address
Note: When the time error between the server and the client is too large (maybe 1000 seconds), the modification time may bring unpredictable problems to the system and application, NTP will stop time synchronization!
Therefore, if you find that the time is not synchronized after NTP starts, you should consider that it may be caused by the large time difference. At this time, you need to manually synchronize the time ntpdate first!
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.