Purpose

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'

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

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

Finally:

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'

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

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

#!/bin/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.