0

I'm aware that this is a very vague question but I'm hopeful someone more knowledgeable can help.

My setup is as follows:

  • I have a simple node docker container
  • I use it to run Node.js scripts from the CLI
  • I want to run these scripts every X with cron

To do this I have the following command:

(cd ~/docker/docker-node && docker compose run --rm -w /home/node/app/scripts docker-node-container npm run my-script)

The above command can be broken down as follows:

  • cd ~/docker/docker-node sets working directory to where my docker-compose.yml file is
  • docker compose run --rm -w /home/node/app/scripts docker-node-container runs a command in a specific working directory within a specific docker container
  • npm run my-script runs the actual Node.js script

I have tested the command from CLI and it runs fine, outputting console logs as expected.

(cd ~/docker/docker-node && docker compose run --rm -w /home/node/app/scripts docker-node-container npm run my-script)

> scripts@0.1.0 my-script > node ./dist/my-script.js

Script is running.

So I went and added it to cron by running sudo crontab -e:

# Run every hour
0 * * * * (cd ~/docker/docker-node && docker compose run --rm -w /home/node/app/scripts docker-node-container npm run my-script)

I then go and check my logs with sudo grep CRON /var/log/syslog:

2024-05-10T08:18:01.787598+00:00 vps CRON[831969]: (root) CMD ((cd ~/docker/docker-node && docker compose run --rm -w /home/node/app/scripts docker-node-container npm run my-script))
2024-05-10T08:18:01.791485+00:00 vps CRON[831968]: (CRON) info (No MTA installed, discarding output)

Not only this doesn't include any of the logs my script is supposed to create but after checking my APIs logs I can tell the script isn't actually hitting any of the endpoints it's supposed to make requests to.

Why?

1 Answers1

3

You've added this to root's crontab. ~ thus refers to /root. The command cd ~/docker/docker-node expands to cd /root/docker/docker-node.

This is probably not what you want. A good idea is to use absolute paths in scripts.

vidarlo
  • 11,723