How can I set up properly a Docker instance to run cronjob tasks
that execute Rails rake tasks
?
I have been trying several things and I have all these problems:
cron.d
file is not loaded Because I have been dealing with all these problems for a while and I haven't find any solution in internet that solved all my problems I am pasting my solution here:
~/MyApp/crontab:
* * * * * root /bin/bash -l -c 'cd $RAILS_ROOT && bundle exec rake my_task' >> /var/log/app_cron.log 2>&1
~/MyApp/Dockerfile:
FROM ruby:2.5.1
# Install dependencies
RUN apt-get update && apt-get -y install cron
# Set an environment variable where the Rails app is installed to inside of Docker image:
ENV RAILS_ROOT /var/www/app
RUN mkdir -p $RAILS_ROOT
# Set our working directory inside the image
WORKDIR $RAILS_ROOT
# Setting env up
ENV RAILS_ENV="production"
ENV RACK_ENV="production"
# Adding gems
COPY Gemfile Gemfile
COPY Gemfile.lock Gemfile.lock
RUN bundle install --jobs 20 --retry 5 --without development test
# Adding project files
COPY . .
## Cron config
# Add crontab file to the cron.d directory
# Files in /etc/cron.d can not have names with "-" or ".". It can be problematic
COPY crontab /etc/cron.d/app
# Give execution rights on the cron job
RUN chmod 0644 /etc/cron.d/app
# To load the env variables in cron sessions
# without this the user in the cron session won't be able to find commands and Gems
RUN printenv | grep -v "no_proxy" >> /etc/environment
# Run the command on container startup
CMD ["cron", "-f"]
For at simpler solution, you could use Arask . It runs timed tasks within Rails itself. No need to use crontab. It runs when rails is running. Just install gem and have your lines in config/initializers/arask.rb, for instance:
arask.create task: 'update:cache', cron: '*/5 * * * *' # Every 5 minutes
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.