Reputation: 2217
I'm setting a cron job that is a bash script containing the below:
#!/bin/bash
NUM_CONTAINERS=$(docker ps -q | wc -l)
if [ $NUM_CONTAINERS -lt 40 ]
then
echo "Time: $(date). Restart containers."
cd /opt
pwd
sudo docker kill $(docker ps -q)
docker-compose up -d
echo "Completed."
else
echo Nothing to do
fi
The output is appended to a log file:
>> cron.log
However the output in the cron file only shows:
Time: Sun Aug 15 10:50:01 UTC 2021. Restart containers.
/opt
Completed.
Both command do not seem to execute as I don't see any change in my containers either. These 2 non working commands work well in a standalone .sh script without condition though. What am I doing wrong?
User running the cron has sudo privileges, and we can see the second echo printing.
Upvotes: 0
Views: 915
Reputation: 881153
Lots of times, things that work outside of cron
don't work within cron
because the environment is not set up in the same way.
You should generally capture standard output and error, to see if something going wrong.
For example, use >> cron.log 2>&1
in your crontab
file, this will capture both.
There's at least the possibility that docker
is not in your path or, even if it is, the docker
commands are not working for some other reason (that you're not seeing since you only capture standard output).
Capturing standard error should help out with that, if it is indeed the issue.
As an aside, I tend to use full path names inside cron
scripts, or set up very limited environments at the start to ensure everything works correctly (once I've established why it's not working correctly).
Upvotes: 2