목표
- Docker 컨테이너 내부에서 파이썬 프로그램을 crontab으로 실행하기
Docker Image 빌드
FROM continuumio/miniconda3
RUN apt-get update && apt-get install -y cron && apt-get autoremove
- crontab을 사용하기 위해 필요한 패키지가 설치되어 있는 이미지 빌드
- 예제에선 docker hub의 miniconda3 이미지를 베이스로 필요한 패키지를 추가로 설치한다
- 예제에서 이미지 이름은 my-images/cron으로 지정한다
crontab 설정 파일 생성
SHELL=/bin/bash
PATH=/opt/conda/bin:/opt/conda/condabin:/opt/conda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
0 15 * * * /opt/conda/bin/python /root/python-scripts/something.py >> /proc/1/fd/1 2>/proc/1/fd/2
# Empty line is required at the end for valid cron file.
- 파일 생성
- 위와 같이 crontab 설정 파일을 생성한다 (예제의 파일명은 cronfile.txt으로 생성)
- Shell 설정
- 환경변수 설정
- cron 내부에서는 호스트의 환경변수를 불러오지 않는다
- 따라서 PATH에 python을 실행시키기 위한 conda와 관련된 디렉토리를 추가한다
- 시간 설정
- 컨테이너 기본 타임존은 UTC이므로, 한국시간(+09:00) 기준 자정에 1번 실행되도록 0 15 * * * 로 설정한다
- 명령어 설정
- python <script location>
- 표준 출력은 /proc/1/fd/1로 보내고, 표준 에러는 /proc/1/fd/2로 보내서 Docker 로그로 기록
Docker Compose 설정
cron:
container_name: cron
image: my-images/cron:latest
volumes:
- "./python-scripts:/root/python-scripts"
- "./cronfile.txt:/etc/cron.d/cronfile.txt"
env_file:
- ./env_file
command: >-
bash -c ". ~/.profile
&& env > /etc/environment
&& crontab /etc/cron.d/cronfile.txt
&& cron -f"
restart: "unless-stopped"
- volumes
- 실행시킬 파이썬 프로그램 또는 디렉토리 mount
- cron 파일 mount
- env_file
- command
- 컨테이너 내부의 cron의 내부 환경에 컨테이너 환경변수를 적용시키려면 /etc/environment에 환경변수를 설정해야 한다
. ~/profile
env > /etc/environment
- crontab 설정 파일 적용
crontab /etc/cron.d/cronfile.txt
- cron 실행 및 컨테이너가 종료되지 않도록 -f 옵션 실행
참고