iAmoric
iAmoric

Reputation: 1965

Run a bash script as cron job in Docker container

I would like to run a bash script periodically inside a Docker container (my work is based on this answer: https://stackoverflow.com/a/37458519/6240756)

Here is my script hello.sh:


#!/bin/sh
echo "Hello world" >> /var/log/cron.log 2>&1

Here is the cron file hello-cron:

# m h  dom mon dow   command
* * * * * /app/hello.sh
# Empty line

And here is my Dockerfile:

FROM ubuntu:20.04

RUN apt-get update && apt-get install -y cron

# Add backup script
COPY hello.sh /app/
RUN chmod +x /app/hello.sh

# Configure the cron
# Copy file to the cron.d directory
COPY hello-cron /etc/cron.d/hello-cron

# Give execution rights on the cron job
RUN chmod 0644 /etc/cron.d/hello-cron

# Apply cron job
RUN crontab /etc/cron.d/hello-cron

# Create the log file to be able to run tail
RUN touch /var/log/cron.log

# Start the cron
CMD cron && tail -f /var/log/cron.log

I build and run the container but nothing happens. I should see "Hello world" displayed every minutes. If I replace the call to the script in the cron file by directly echo "Hello world" >> /var/log/cron.log 2>&1 it works, I see "Hello world" every minutes

What am I doing wrong?

EDIT

And the Docker commands:

docker build -t hello-cron .
docker run -t -i hello-cron

Upvotes: 2

Views: 6635

Answers (1)

Alejandro Galera
Alejandro Galera

Reputation: 3691

About your concrete question

The problem is that you're launching your docker with -t -i, and what you want is a background execution and check it interactively.

Try with:

docker run -d --name mycontainer hello-cron 
docker logs -f mycontainer

Best practices

If you are going to execute something periodically, consider if it should be in healthcheck definition, where you can set period and other variables.

Second, note that your cron.log is not mounted, so, you'd lose this info if docker restart.

Upvotes: 1

Related Questions