Cron job in AWS ECS EC2 docker instance

I needed to be able to run a cron job within a docker container hosted on an AWS EC2 instance using their Elastic Container Service (ECS).

The bitnami docker image I was using didn’t contain cron, which meant I had to install it using the Dockerfile.

Dockerfile with cron job

This is how I added it;

# Get the bitnami image
FROM bitnami/php-fpm:7.3-prod

# Update and install cron
RUN apt-get update && apt-get -y install cron

# Copy the cron job file from my local computer to docker container instance
COPY main/cron/my-cron-file /etc/cron.d/my-cron-file

# Set execution rights
RUN chmod 0755 /etc/cron.d/my-cron-file

# Run the cron command
CMD /usr/sbin/cron -f

Cron job file ran by the cron job

My cron job file looks like this;

*/5 * * * * root /opt/bitnami/php/bin/php -f /app/cron/schedule.php > /var/log/cron-schedule.log 2>&1

Make sure you have an empty space (carriage return) in the end of the cron job file. Went through a lot of pain before I realised that I was missing an empty space.

*/5 * * * * means the job runs every five minutes.

I had to specify the root user in order for it to run. The output of the cron job is logged in a separate file called /var/log/cron-schedule.log

2>&1 indicates that both standard error (2>) and standard output are output (&1) will be redirected to the specified file

Leave a Comment