I've got a php container which hosts a Symfony web application. I need to use background scripts and initiate them from crontab. And it seems to work as long as I use root user. However, when I switch user to "www-data" - it stops working. My idea was to run php-fpm as user www-data and also log into "www-data" when I enter to the container. But crontab can be defined for root user, since it allows to prefix commands with username.
my entry point file contains:
#!/bin/bash
npm install
cron &
php-fpm
and my docker file looks like this:
WORKDIR /app
ADD ./entrypoint.sh /entrypoint.sh
RUN chmod 777 /entrypoint.sh
ADD ./crontab.txt /etc/cron.d/hello-cron
RUN chmod 0666 /etc/cron.d/hello-cron
RUN crontab /etc/cron.d/hello-cron
RUN touch /var/log/cron.log
RUN usermod -s /bin/bash www-data
USER www-data
ENTRYPOINT /entrypoint.sh
The above works if I skip line
USER www-data
But I would like to first initiate cron (for root) and later switch default container user to www-data... so I've tried also:
ENTRYPOINT /entrypoint.sh
USER www-data
But it doesn't work as well. Any help will be appreciated :)
The issue I encountered in such scenario is that when you run container using unprivileged user you cannot start cron due to lack of access to cron.pid file.
Therefore the best workaround is to set SUID for the cron binary which will allow to run it with root privileges using your www-data user. You should also make sure to add cron settings to the correct user's crontab.
You can modify your Dockerfile in a following way:
WORKDIR /app
ADD ./entrypoint.sh /entrypoint.sh
RUN chmod 777 /entrypoint.sh
ADD ./crontab.txt /etc/cron.d/hello-cron
RUN crontab -u www-data /etc/cron.d/hello-cron  # <---- setting crontab for user www-data
RUN chmod u+s /usr/sbin/cron  # <---- setting setuid
RUN touch /var/log/cron.log
RUN usermod -s /bin/bash www-data
USER www-data
ENTRYPOINT /entrypoint.sh
This should work just fine.
You can simply remove USER www-data row in Dockerfile and change /entrypoint.sh file as bellow
#!/bin/bash
npm install
cron
su www-data
php-fpm
After adding su www-data command you switch user to www-data and if you log into container your default user will be www-data
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With