在Docker中運(yùn)行crontab
2019-02-17 20:13:41
17675
在把自己的項(xiàng)目通過Docker進(jìn)行打包時(shí),由于項(xiàng)目中用到了crontab,不過使用到的基礎(chǔ)鏡像Python:3.6-slim并沒有安裝這項(xiàng)服務(wù),記錄下在鏡像中安裝和配置crontab的過程。
Dockerfile
由于基礎(chǔ)鏡像中沒有crontab服務(wù),需要在打包自己鏡像的Dockerfile中加入安裝cron服務(wù)的步驟。
FROM python:3.6-slim
MAINTAINER linuxidc root@landui.com
RUN apt-get update && \
apt-get install -y --no-install-recommends \
cron && \
rm -rf /var/lib/apt/lists/* && \
apt-get clean
RUN chmod +x ./docker-entrypoint.sh
ENV LC_ALL C.UTF-8
ENTRYPOINT ["./docker-entrypoint.sh"]
執(zhí)行apt安裝時(shí)注意加入-y --no-install-recommends,并且在安裝完成后執(zhí)行rm -rf /var/lib/apt/lists/* && apt-get clean命令,可以有效減小鏡像的體積。
這樣安裝完cron服務(wù)后,crontab服務(wù)并不會(huì)自啟動(dòng),還需要一個(gè)docker-entrypoint.sh啟動(dòng)腳本來添加crontab的啟動(dòng)命令。
啟動(dòng)腳本
#!/bin/bash
set -x
# 保存環(huán)境變量,開啟crontab服務(wù)
env >> /etc/default/locale
/etc/init.d/cron start
/etc/init.d/cron start用于啟動(dòng)crontab服務(wù),但這樣啟動(dòng)的crontab服務(wù)中配置的定時(shí)命令是沒有Dockerfile中設(shè)置的環(huán)境變量的。因此還需要在這之前執(zhí)行env >> /etc/default/locale,這樣有Dockerfile中通過ENV設(shè)置的環(huán)境變量在crontab中就可以正常讀取了。