How to write solid cron jobs
Recently I migrate pypi-mirrors from Vultr VPS to Rancher stack, which is a pure container environment. Everything work fine, though it took me some time to setup the cron job in container correctly. And here is a short summary which might need keep in mind while using cron job inside a container.
1. Environment Variables
Since docker containers variables were set via parameters during the container start. It’s not very easy be accessed from the cron job, because the environment variables are always inside the process whose pid is 1 and can not be read outside the process directly.
2. Use absolute path as much as possible
For example, prefer to use
/usr/local/bin/python rather than
python as much as possible. In most cases, this will save you time to figure out the
3. Do necessary logging
Output useful information to stdout/stderr, this will help you when bad thing happens.
4. Properly redirect
In most cases, using something like
> /var/log/xxx.log 2>&1 would help you observe if your cron jobs are running as expected.
. instead of
/bin/sh is not always equal to
. to do a source is much safer.
If you really not sure wether your cron job is running, try to install
rsyslog, then uncomment the
cron related logging. Then you’ll see something in
/var/log/cron.log, which might be useful.