背景
在搭建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 fudge 127.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
