Docker Swarm: Preflight Checks to ensure a directory exists

Sometimes, it’s desirable to store logs or other files on the host itself. To do this with Swarm, you’ll need to ensure the directory exists on the host so you can bind mount it into your log-producing containers. In this example, we’ll assume we want to bind-mount /opt/my-app-logs on the host.

Replicated YAML

Add an item to custom_requirements to declare the preflight check and define its messaging.

# kind: replicated
custom_requirements:
- id: logdir-exists
  message: Log Directory Exists
  details: Log Directory /opt/my-app-logs must exist on the host
  results:
    - status: success
      message: Directory /opt/my-app-logs exists
      condition:
        status_code: 0
    - status: error
      message: Directory /opt/my-app-logs does not exist, please create this directory before proceeding
      condition:
        status_code: 1
  command:
    id: scheduler
    timeout: 10
    data:
      swarm:
        service: "check-dir" # matches the Service name below

Preflight-Swarm section

After your # kind: scheduler-swarm section, you’ll want to create another YAML with the metadata tag # kind: preflight-swarm. The service name should match the service name above.

---
# kind: preflight-swarm
version: "3"
services:
  check-dir:
    image: busybox:latest
    volumes:
      - "/opt:/host/opt"
    command: ["test","-d","/host/opt/my-app-logs"]