使用容器化部署 NTP

背景

在系统运维中,尤其是针对Kunbernetes集群环境,时间的一致性至关重要,然而在不同的发行版本及不同的平台下面面对这些依赖也是一件难过的事情。为避免依赖,我们可以使用容器化来规避它。

配置札记

避免造轮,我们使用 cturra/ntp:latest 容器镜像,找到它的源头,做些微调:

git clone --depth=1 https://github.com/cturra/docker-ntp.git
  • dockerfile
FROM alpine:3.17

ARG BUILD_DATE

LABEL build_info="registry.cn-shenzhen.aliyuncs.com/shuhui/chrony build-date:- ${BUILD_DATE}"
LABEL maintainer="Qiu Shuhui <shuhui@vqiu.cn>"
LABEL documentation="https://github.com/cturra/docker-ntp"

RUN set -xe \
    && sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories \
    && apk add --no-cache chrony tzdata \
    && cp -rf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
    && echo "Asia/Shanghai" > /etc/timezone

COPY assets/startup.sh /opt/startup.sh


EXPOSE 123/udp

HEALTHCHECK CMD chronyc tracking || exit 1

ENTRYPOINT [ "/bin/sh", "/opt/startup.sh" ]

容器默认使用的是time.cloudflare.com,我们将它改成国内的NTP

  • assets/startup.sh
#!/bin/sh

# 参考:http://www.ntp.org.cn/
DEFAULT_NTP="CN.NTP.ORG.CN"

构建镜像

# ./build.sh
或直接使用registry.cn-shenzhen.aliyuncs.com/shuhui/chrony:latest

运行

#  docker run --name=ntp                           \
              --detach=true                        \
              --restart=always                     \
              --publish=123:123/udp                \
              --env=NOCLIENTLOG=no                 \
              --env=LOG_LEVEL=0                    \
              --read-only=true                     \
              --tmpfs=/etc/chrony:rw,mode=1750     \
              --tmpfs=/run/chrony:rw,mode=1750     \
              --tmpfs=/var/lib/chrony:rw,mode=1750 \
              registry.cn-shenzhen.aliyuncs.com/shuhui/chrony:latest

查看容器运行日志

2023-06-03T02:31:18Z chronyd version 4.3 starting (+CMDMON +NTP +REFCLOCK +RTC +PRIVDROP -SCFILTER +SIGND +ASYNCDNS +NTS +SECHASH +IPV6 -DEBUG)
2023-06-03T02:31:18Z Disabled control of system clock
2023-06-03T02:31:22Z Selected source 1.14.61.51 (cn.ntp.org.cn)
2023-06-03T12:00:00Z Forward time jump detected!
2023-06-03T12:00:00Z Can't synchronise: no selectable sources
2023-06-03T02:33:18Z Backward time jump detected!
2023-06-03T02:36:33Z Selected source 1.14.61.51 (cn.ntp.org.cn)
2023-06-08T06:56:39Z chronyd exiting
2023-06-08T06:56:54Z chronyd version 4.3 starting (+CMDMON +NTP +REFCLOCK +RTC +PRIVDROP -SCFILTER +SIGND +ASYNCDNS +NTS +SECHASH +IPV6 -DEBUG)
2023-06-08T06:56:54Z Disabled control of system clock
2023-06-08T06:56:59Z Selected source 1.14.61.51 (cn.ntp.org.cn)
2023-06-08T07:44:23Z chronyd exiting
2023-06-08T07:44:38Z chronyd version 4.3 starting (+CMDMON +NTP +REFCLOCK +RTC +PRIVDROP -SCFILTER +SIGND +ASYNCDNS +NTS +SECHASH +IPV6 -DEBUG)
2023-06-08T07:44:38Z Disabled control of system clock
2023-06-08T07:44:43Z Selected source 1.14.61.51 (cn.ntp.org.cn)

操作系统中有个配置会影响到NTP是否能干预系统时间:

# timedatectl set-ntp true
须知:若为false ntp 是无法修改系统时间的