rails,每当 docker - cron 任务不会 运行

rails, whenever and docker - cron tasks doesn't run

我来自 schedule.rb 的 crontasks 不能在 docker 容器上运行,但是 crontab -l 结果已经包含这些行:

# 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

我可以 运行 在容器中手动执行此命令并且它有效。似乎 cron 没有启动。

Docker 文件:

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

在 Dockerfile 中,运行 命令仅在构建镜像时执行。

如果您想在启动容器时启动 cron,您应该 运行 cron in CMD。我通过删除 RUN service cron start 并更改 ENTRYPOINT.

修改了您的 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
CMD cron && bundle exec puma

最好的做法是减少图像的层数,例如,您应该始终将 运行 apt-get update 与 apt-get install 结合在同一个 运行 语句中,并在以下时间后清理 apt 文件: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