I am trying to get a cronjob to run as non root user. This cronjob should really running a python script and write some files. I’d also like to see the output of the cronjob in the docker logs.
Here is an initial attempt where I run the cron as myuser
.
FROM continuumio/miniconda3:latest
# Install cron
RUN apt-get update && apt-get -y install cron
# Create a user with a specific UID and GID (replace 1000 with the desired UID and GID)
RUN groupadd -g 1006 myuser && useradd -u 1006 -g 1006 myuser
# Write the crontab file and install it
RUN echo "* * * * * myuser echo 'WEEEEE' > /proc/1/fd/1 2>/proc/1/fd/2" >> /etc/crontab
# Start cron in the foreground
CMD ["cron", "-f", "-l", "2"]
This results in nothing being printed to the docker logs:
~/docker_test$ docker build . -t test-cron
Sending build context to Docker daemon 12.8kB
Step 1/5 : FROM continuumio/miniconda3:latest
---> fbedfde8d058
Step 2/5 : RUN apt-get update && apt-get -y install cron
---> Using cache
---> 678562a4310d
Step 3/5 : RUN groupadd -g 1006 myuser && useradd -u 1006 -g 1006 myuser
---> Running in 3900a0e8b4b4
Removing intermediate container 3900a0e8b4b4
---> 88700a4f5e80
Step 4/5 : RUN echo "* * * * * myuser echo 'WEEEEE' > /proc/1/fd/1 2>/proc/1/fd/2" >> /etc/crontab
---> Running in 82d2f2736673
Removing intermediate container 82d2f2736673
---> 4a4a6193881e
Step 5/5 : CMD ["cron", "-f", "-l", "2"]
---> Running in a50eaf745b75
Removing intermediate container a50eaf745b75
---> 008da0fec723
Successfully built 008da0fec723
Successfully tagged test-cron:latest
~/docker_test$ docker run --name test-cron-container test-cron
If I run it as root, however, by changing the line
RUN echo "* * * * * myuser echo 'WEEEEE' > /proc/1/fd/1 2>/proc/1/fd/2" >> /etc/crontab
to
RUN echo "* * * * * root echo 'WEEEEE' > /proc/1/fd/1 2>/proc/1/fd/2" >> /etc/crontab
it works. I understand that myuser
does not have permissions to write to /proc/1/fd/1
.
I’ve seen this answer but I cannot reproduce his results of seeing the outputs in the terminal.
How to run a cron job as a non-root user and log the job's output?
2
Answers
I all you wanted to do is to run
echo 'WEEEEE'
as myuser, you can change Dockerfile to:I might be off here but the docker book I’ve just finished reading says to use outside stuff to limit containers to "one service" or one job as one says.
They even have a cron example in there. You cron on the host with
docker exec CONTAINERNAME COMMAND
I quickly tried this on my machine and it works, with our without -i -t or -it.Also, your dockerfile has 3 RUN commands back to back. This expands the size of your image massively as every command is a layer. You should be able to make these into one using
&&
and.
Good luck.