Docker,Rails和cron任务:如何设置Docker容器以运行cron Rails rake任务

时间:2018-07-07 14:27:38

标签: ruby-on-rails docker cron

如何正确设置一个运行cronjob tasks并执行Rails rake tasks的Docker实例?

我一直在尝试几件事,但遇到了所有这些问题:

  • cron.d文件未加载
  • 如果cron任务失败,则没有日志
  • cron任务会话中的环境为空

2 个答案:

答案 0 :(得分:0)

因为一段时间以来我一直在处理所有这些问题,而我在互联网上找不到任何解决所有问题的解决方案,所以我将解决方案粘贴在这里:

〜/ 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"]

答案 1 :(得分:0)

对于更简单的解决方案,您可以使用link。它在Rails本身中运行定时任务。无需使用crontab。 它在导轨运行时运行。只需安装gem,然后将行放在config / initializers / arask.rb中,例如:

arask.create task: 'update:cache', cron: '*/5 * * * *' # Every 5 minutes