Docker Swarm : cronjobs

less than 1 minute read

One of the shortcomings that Docker Swarm has compare to Kubernetes, is the possibility to schedule jobs natively.

Fortunately a project called swarm-cronjob from crazy-max allow you to schedule jobs in Docker Swarm.

Setup

Swarm-cronjob get deployed using the following stack file (swarm-cronjob.yaml):

version: "3.4"

services:

  swarm-cronjob:
    image: crazymax/swarm-cronjob:latest
    networks:
      - backend
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock"
    environment:
      - "TZ=Europe/Paris"
      - "LOG_LEVEL=info"
      - "LOG_JSON=false"
    deploy:
      placement:
        constraints:
          - node.role == manager

networks:
  backend:
    external: true

Once swarm-cronjob is successfully deployed, it is time to schedule a job.
Let’s say you want a job that hit an API endpoint every morning at 08:00.
The stack file will then looks like this (cronjob-hit-an-api.yaml):

version: "3.4"

services:

  cronjob-hit-an-api:
    image: ellerbrock/alpine-bash-curl-ssl:latest
    networks:
      - backend
    command: curl -X POST https://reqbin.com/echo/post/json
    deploy:
      mode: replicated
      replicas: 0
      labels:
        - "swarm.cronjob.enable=true"
        - "swarm.cronjob.schedule=00 08 * * *"
        - "swarm.cronjob.skip-running=false"
      restart_policy:
        condition: none

networks:
  backend:
    external: true

Swarm-cronjob will then detect via the docker socket that a new service (cronjob-hit-an-api) was added.
It is done by sniffing specific labels, similair to what Traefik is doing for example.
Tailing swarm-cronjob service log files you can see that the job was added.

References

Updated: