0

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.

1 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

5 Comments

The user for this cron has sudo privilege. Also the echo just after should not show if that was the case
@Vincent: good point, I should have realised that. I've changed the answer from the original, based on that.
And you are absolutely right.... by not capturing the error output I couldn't see that: "docker-compose: command not found"
@Vincent: interesting. That sits alongside docker in /usr/bin, at least on my system. Not sure where it's gone on yours. ... Actually, never mind, it looks like a separate package under Linux proper. You may have to install it over and above docker itself. I didn't have to because the Win/WSL one does it automagically.
/usr/local/bin/ in my case (Ubuntu 20.04)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.