The purpose of this post is to help developers/sysadmins to run their programmed tasks very easily using docker. These are some examples that could be useful:

  • Backup databases creating dumps weekly, every x days or even every x hours.
  • Run database/OS maintenance tasks periodically.
  • Retrieving data from a 3rd party making API calls periodically.
  • Keeping distributed content synced using Rsync.. and many more.

Before you begin

In this tutorial will learn how to run tasks periodically on a Docker Alpine container. A Linux/Mac OS/Windows machine with Docker installed is required to follow this tutorial.

Execute cron tasks hourly

By default crond installation on Alpine Linux contains the following folders:

$ docker run -it alpine ls /etc/periodic
15min    daily    hourly   monthly  weekly

Where you can choose when to run a task placing scripts on each folder.

Following previous conventions, you can use the following docker-compose example to run tasks placed in your cron_tasks_folder folder hourly:

version: '2'

    image: alpine:3.6
    command: crond -f -l 8
      - ./cron_tasks_folder:/etc/periodic/hourly/:ro

Scripts inside of cron_tasks_folder have to be without extension and with +x permissions.


docker-compose build
docker-compose run -d

Bonus track: How to backup a PostgreSQL daily

To backup a PostgreSQL database you can use the following docker-compose:

version: '2'

    image: postgres:9.6
      - /var/opt:/var/lib/postgresql
      - PGDATA=/var/lib/postgresql/pg_data
    image: postgres:9.6-alpine
    command: crond -f -l 8
      - ./cron_tasks_folder:/etc/periodic/daily/:ro
      - /host_dumps_folder/:/var/opt/
      - db

Include the following file ./cron_tasks_folder/dump (Remember to not include the file extension .sh):


pg_dump -h db -U POSTGRES_USER POSTGRES_DB >> /var/opt/$(date +"%Y%m%d%H%M%S").sql

And finally run Docker:

docker-compose build
docker-compose run -d

More information about how to backup a Postgres database using Docker here.