Rails when and docker - cron jobs won't run
My crontasks from schedule.rb
don't work in a docker container, but the result crontab -l
already contains the following lines:
# Begin Whenever generated tasks for: /app/config/schedule.rb
45 19 * * * /bin/bash -l -c 'bundle exec rake stats:cleanup'
45 19 * * * /bin/bash -l -c 'bundle exec rake stats:count'
0 5 * * * /bin/bash -l -c 'bundle exec rake stats:history'
# End Whenever generated tasks for: /app/config/schedule.rb
I can run these commands manually in the container and it works. It seems that cron is not starting.
Dockerfile:
FROM ruby:2.4.0-slim
RUN apt-get update
RUN apt-get install -qq -y --no-install-recommends build-essential libpq-dev cron postgresql-client
RUN cp /usr/share/zoneinfo/Europe/Moscow /etc/localtime
ENV LANG C.UTF-8
ENV RAILS_ENV production
ENV INSTALL_PATH /app
RUN mkdir $INSTALL_PATH
RUN touch /log/cron.log
ADD Gemfile Gemfile.lock ./
WORKDIR $INSTALL_PATH
RUN bundle install --binstubs --without development test
COPY . .
RUN bundle exec whenever --update-crontab
RUN service cron start
ENTRYPOINT ["bundle", "exec", "puma"]
source to share
In a Dockerfile, the RUN command is only executed when the image is created.
If you want to run cron when your container starts, you must run cron
in CMD
. I modified your Dockerfile by deleting RUN service cron start
and changing yours ENTRYPOINT
.
FROM ruby:2.4.0-slim
RUN apt-get update
RUN apt-get install -qq -y --no-install-recommends build-essential libpq-dev cron postgresql-client
RUN cp /usr/share/zoneinfo/Europe/Moscow /etc/localtime
ENV LANG C.UTF-8
ENV RAILS_ENV production
ENV INSTALL_PATH /app
RUN mkdir $INSTALL_PATH
RUN touch /log/cron.log
ADD Gemfile Gemfile.lock ./
WORKDIR $INSTALL_PATH
RUN bundle install --binstubs --without development test
COPY . .
RUN bundle exec whenever --update-crontab
CMD cron && bundle exec puma
Your best bet is to reduce the number of image layers, for example, you should always combine a RUN apt-get update with apt-get install in the same RUN statement and clean up the apt files after: rm -rf /var/lib/apt/lists/*
FROM ruby:2.4.0-slim RUN apt-get update && \ apt-get install -qq -y --no-install-recommends build-essential libpq-dev cron postgresql-client \ rm -rf /var/lib/apt/lists/* && \ cp /usr/share/zoneinfo/Europe/Moscow /etc/localtime ENV LANG C.UTF-8 ENV RAILS_ENV production ENV INSTALL_PATH /app RUN mkdir $INSTALL_PATH && \ touch /log/cron.log ADD Gemfile Gemfile.lock ./ WORKDIR $INSTALL_PATH RUN bundle install --binstubs --without development test COPY . . RUN bundle exec whenever --update-crontab CMD cron && bundle exec puma
source to share