unable to run R script in crontab in docker container

I'm trying to run a R script inside docker container. Here is the example.

My working directory is like below.


In the directory myRDocker, there is a dockerfile and a directory scripts, which contains a R script save_iris.R

My R script save_iris.R is like below:

write.csv(iris, '/data/iris.csv')

My dockerfile is like below:

# Install R version 3.6
FROM r-base:3.6.0

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

RUN mkdir /data
COPY /scripts  /scripts

I went to my directory myRDocker and build docker image

docker build -t baser .

I run the docker container in bash.

docker run -it baser bash

After I get into the container, I did:

crontab -e

then add this line, then save

* * * * * Rscript /scripts/save_iris.R

It should save the file to the folder /data every min. However, I never found any file in the data folder inside the container.

My question is:

  1. what did I do wrong in the above procedure? I feel like I might be missing something.... but could not figure out why...

  2. what should I do if I want to run the scheduled cron task whenever container start. (something like put the cron task in a file, and run when container start....)

1 answer

  • answered 2019-10-09 07:00 Adiii

    why you are not starting the cronjob on container run time, instead of running after container start? Also, I do not think the crontab process will run in your case as your container is not doing any thing.

    Try this, which will start cron on container run time and will also tail logs of cron job. but keep in mind your main process in this case is tail -f /var/log/cron.log not the cron process.

     FROM r-base:3.6.0
     RUN apt-get update &&  apt-get -y install cron
     RUN touch /var/log/cron.log
     COPY hello.r /hello.r
     RUN (crontab -l ; echo "* * * * * Rscript /hello.r  >> /var/log/cron.log") | crontab
    # Run the command on container startup
     CMD cron && tail -f /var/log/cron.log

    So you will get the Rscript console logs to Container stdout.


    print("Hello World from R")

    enter image description here