daicky777
daicky777

Reputation: 103

How can I execute cron task as a non-root user within the rails docker container?

I'm trying to use cron as a non-root user in the docker container. The container already has rails application by the non-root user and I want to execute cron tasks as the same user while getting rails server running at the same time. However, when I run docker-compose up -d I get an error saying cron: can't open or create /var/run/crond.pid: Permission denied

So my question is if there is any way to execute cron task as non-root user in the container that has rails application. Just so you know I tried not to use root account for a security reason. Thank you in advance!

Here is my dockerfile bedow ...

FROM ruby:2.5

RUN apt-get update -qq && apt-get install -y --no-install-recommends \
    build-essential \
    libpq-dev \
    nodejs \
    cron \
    && rm -rf /var/lib/apt/lists/* \
    && apt-get clean

ENV \
 USER=new_user \
 GROUP=new_user \
 APP_ROOT=/var/www/new_user \
 HOME=/home/new_user \
 RAILS_PATH=./apps/server/new_user

RUN groupadd $GROUP && \
 useradd -g $GROUP $USER

RUN mkdir -p $APP_ROOT && \
 mkdir -p $HOME

WORKDIR $APP_ROOT

COPY $RAILS_PATH/Gemfile .
COPY $RAILS_PATH/Gemfile.lock .
COPY $RAILS_PATH/config/puma.rb config/puma.rb
COPY $RAILS_PATH/config/schedule.rb config/schedule.rb

RUN \
 gem update --system && \
 gem install bundler && \
 bundle config --global build.nokogiri --use-system-libraries && \
 bundle config --global jobs 2 && \
 bundle install --path=vendor/bundler

RUN \
 chown -R $USER $HOME && \
 chown -R $USER $APP_ROOT && \
 chgrp -R $GROUP $APP_ROOT && \
 chgrp -R $GROUP $APP_ROOT

USER $USER

RUN bundle exec whenever --update-crontab

CMD cron -f && bundle exec puma -C config/puma.rb

...

Upvotes: 1

Views: 999

Answers (1)

Esben Damgaard
Esben Damgaard

Reputation: 318

You could use the gem arask instead of whenever. It runs tasks within Rails, so the user is the same. Just reference your tasks from config/initializers/arask.rb instead and forget about running cron.

Upvotes: 1

Related Questions