Thursday, 5 December 2019

docker run cron

https://stackoverflow.com/questions/37458287/how-to-run-a-cron-job-inside-a-docker-container

https://blog.knoldus.com/running-a-cron-job-in-docker-container/


---
Dockerfile:
---


FROM mongo:latest

MAINTAINER Ping Wang

# Install cron
RUN apt-get update && apt-get install -y cron

# Add files
ADD docker_cron_run.sh /docker_cron_run.sh
ADD docker_entrypoint.sh /docker_entrypoint.sh

RUN chmod +x /docker_cron_run.sh /docker_entrypoint.sh

RUN touch /var/log/cron.log

CMD /docker_entrypoint.sh && tail -f /var/log/cron.log




---
docker_entrypoint.sh file:
---


#!/bin/bash

# Start the run once job.
echo "Docker container has been started"

declare -p | grep -Ev 'BASHOPTS|BASH_VERSINFO|EUID|PPID|SHELLOPTS|UID' > /container.env

echo "start" >> /var/log/cron.log 2>&1

# Setup a cron schedule
echo "SHELL=/bin/bash
BASH_ENV=/container.env
* * * * * /docker_cron_run.sh >> /var/log/cron.log 2>&1
# This extra line makes it a valid cron" > scheduler.txt

crontab scheduler.txt
cron

echo "running....."



---
docker_cron_run.sh:    here is what you actually want to do 
---

#!/bin/bash
timestamp=`date +%Y/%m/%d-%H:%M:%S`

echo "System path is $PATH at $timestamp"




then run:


docker build -t mycorn:15 .

then run:


docker run mycorn:15

then it will run and output logs into the log file and it also output logs into the current terminal.




i found cron -f which makes cron running on the foreground, but it will also stop output to terminal.

which means you r tail -f xxxx will not work and if you use kubernates, you will not able to use kubctl to get logs.








No comments:

Post a comment