jinquan26 发表于 2017-12-6 18:31:05

docker 搭建ntp服务器

背景
  在搭建etcd集群时,如果主机时间相差太多会出现同步错误,如果外部网络不可用时,需要使用内部的ntp服务器同步时间。

构建ntp镜像

创建Dockerfile



# usage:
#      docker build -t ntp .
#      docker run docker run -d --name ntp-server -p 123:123 -v /etc/localtime:/etc/localtime:ro -v /etc/timezone:/etc/timezone:ro ntp
from nginx
RUN sed -i s/archive.ubuntu.com/mirrors.aliyun.com/g /etc/apt/sources.list \
&& sed -i s/security.ubuntu.com/mirrors.aliyun.com/g /etc/apt/sources.list \
&& apt-get update
RUN apt-get install ntp -y
ADD ./entrypoint.sh /bin/entrypoint.sh
ADD ./ntp.conf /etc/ntp.conf
# ENTRYPOINT ["/etc/init.d/ntp", "start"]
CMD ["sh", "/bin/entrypoint.sh"]
创建entrypoint.sh文件



/etc/init.d/ntp start
nginx -g 'daemon off;'
创建npt.conf



restrict default nomodify notrap noquery
restrict 127.0.0.1
restrict 192.168.0.0 mask 255.255.255.0 nomodify
restrict 10.10.10.0 mask 255.255.255.0 nomodify
#server 0.pool.ntp.org
#server 1.pool.ntp.org
#server 2.pool.ntp.org
server 127.127.1.0    # local clock
fudge127.127.1.0 stratum 10
driftfile /var/lib/ntp/drift
broadcastdelay 0.008
构建镜像



docker build -t ntp .
启动ntp服务器



docker run -d --name ntp-server -p 123:123 -v /etc/localtime:/etc/localtime:ro -v /etc/timezone:/etc/timezone:ro ntp
  查看服务状态



docker exec -it ntp-server service ntp status
客户端配置
  当前运行容器不需要配置客户端
  客户端与服务端不能在同一台机器上运行
  目前的服务器是用主机的时间作为标准时间的

安装ntpdate



sudo apt-get install ntpdate
同步主机时间



sudo ntpdate 192.168.0.20
  这里的ip是ntp容器运行的主机

配置定时任务更新时间
  通过如下命令,就可以开启本用户的定时文件,文件存放在 /var/spool/cron/crontabs 文件夹下,并且以用的的名字命名的文件
  可以通过以下命令列出某个用户cron服务的详细内容



crontab -l
  通过以下命令编辑定时任务



crontab -e
  在文件末尾增加



* * * * * ntpdate 192.168.0.20
  一些常用周期



每五分钟执行*/5 * * * *
每小时执行   0 * * * *
每天执行      0 0 * * *
每周执行       0 0 * * 0
每月执行      0 0 1 * *
每年执行       0 0 1 1 *
  重启定时任务服务



sudo service cron restart
  查看日志



journalctl -n 10 -f -u cron
页: [1]
查看完整版本: docker 搭建ntp服务器