1

I have been trying to run a cron job within my docker container and I can't seem to get the cron service to run when the container is started. I can remote into the running container and run "cron" to get the service to start without issues. I have this included in my DockerFile, why is the command not being executed?

I am able to get it to work by doing the following (as described above):

docker-compose build
docker-compose up -d
docker exec -it my_container /bin/bash
root@2348723ae34: /etc/init.d/cron status <--check cron service status
[FAIL] cron is not running ... failed!  <--- cron not running
root@2348723ae34: cron
[ ok ] cron is running. <-- simply running cron starts the service

crontab file

*/2 * * * * rm -rf /usr/src/app/assets/aligned_output/* && rm -rf /usr/src/app/assets/aligned_input/*

DockerFile

FROM node:latest

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY . /usr/src/app

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

# Add crontab file in the cron directory
ADD crontab /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

# Run the command on container startup
CMD cron && tail -f /var/log/cron.log

RUN touch /etc/crontab /etc/cron.*/*

EXPOSE 80
RUN npm install
CMD ["npm", "start"]

docker-compose.yml

inventory:
   build: .
   restart: always
   command: npm start
   ports:
   - "80:80"
   environment:
      - NODE_ENV=production
Sam Munroe
  • 1,266
  • 2
  • 20
  • 41
  • I suspect (guess!) that the second `CMD` (only) is what's effected. This would explain (I assume) that your Node apps is running but cron isn't. Can you separate the two processes into their own containers? You'll need to run cron in the foreground in its container so that the container doesn't immediately exit. – DazWilkin Mar 06 '19 at 18:53

1 Answers1

0

By default, docker will run onlt the CMD process. One hack is, add one entrypoint script that will run cron in background and then invoke CMD node application. But I will prefer running two containers, one for CRON and other for application that will help in separating out concerns fir containers. One container will run cron as CMD and other run node application.

In case you want to share filesystem that is possible using volume mounts.

Akash Sharma
  • 721
  • 3
  • 6