June 20-22 Announcing HashiConf Europe full schedule: keynotes, sessions, labs & more Register Now
  • Overview
    • Batch Processing Workloads
    • Edge Workload Management
    • Non-Containerized Application Orchestration
    • Simple Container Orchestration
  • Enterprise
  • Tutorials
  • Docs
  • API
  • Plugins
  • Tools
  • Community
GitHub—Stars on GitHub
Download
    • v1.3.x (latest)
    • v1.2.x
    • v1.1.x
    • v1.0.x
    • v0.12.x
    • v0.11.x
    • Overview
    • Quickstart
      • Overview
      • Requirements
      • Reference Architecture
      • Deployment Guide
    • Windows Service
    • Overview
    • Specific Version Details
    • Overview
    • Consul
    • Consul Service Mesh
    • Vault Integration

    • Overview
    • Architecture
      • Overview
      • Base
      • Task Drivers
      • Devices
      • Storage
      • Overview
      • Internals
      • Preemption
    • Consensus Protocol
    • Filesystem
    • Gossip Protocol
    • Security Model
    • Overview
    • acl
    • audit
    • autopilot
    • client
    • consul
    • plugin
    • sentinel
    • search
    • server
    • server_join
    • telemetry
    • tls
    • ui
    • vault
    • Overview
      • Overview
      • bootstrap
      • policy apply
      • policy delete
      • policy info
      • policy list
      • token create
      • token delete
      • token info
      • token list
      • token self
      • token update
    • agent
    • agent-info
      • Overview
      • exec
      • fs
      • logs
      • restart
      • signal
      • status
      • stop
      • Overview
      • validate
      • Overview
      • fail
      • list
      • pause
      • promote
      • resume
      • status
      • unblock
      • Overview
      • list
      • status
      • Overview
      • allocs
      • deployments
      • dispatch
      • eval
      • history
      • init
      • inspect
      • plan
      • periodic force
      • promote
      • revert
      • run
      • scale
      • scaling-events
      • status
      • stop
      • validate
      • Overview
      • get
    • monitor
      • Overview
      • apply
      • delete
      • inspect
      • list
      • status
      • Overview
      • config
      • drain
      • eligibility
      • status
      • Overview
      • api
      • autopilot get-config
      • autopilot set-config
      • debug
      • keygen
      • keyring
      • metrics
      • raft info
      • raft list-peers
      • raft logs
      • raft remove-peer
      • raft state
      • snapshot agent
      • snapshot inspect
      • snapshot restore
      • snapshot save
      • snapshot state
      • Overview
      • status
      • Overview
      • apply
      • delete
      • init
      • inspect
      • list
      • status
      • Overview
      • apply
      • dismiss
      • info
      • list
      • Overview
      • policy info
      • policy list
      • Overview
      • apply
      • delete
      • list
      • read
      • Overview
      • force-leave
      • join
      • members
      • Overview
      • service delete
      • service info
      • service list
    • status
      • Overview
      • gc
      • reconcile summaries
    • ui
    • version
      • Overview
      • create
      • delete
      • deregister
      • detach
      • init
      • register
      • snapshot create
      • snapshot delete
      • snapshot list
      • status

    • Overview
      • Overview
      • Expressions
        • Overview
          • chunklist
          • coalesce
          • coalescelist
          • compact
          • concat
          • contains
          • distinct
          • element
          • flatten
          • index
          • keys
          • length
          • lookup
          • merge
          • range
          • reverse
          • setintersection
          • setproduct
          • setunion
          • slice
          • sort
          • values
          • zipmap
          • can
          • convert
          • try
          • bcrypt
          • md5
          • rsadecrypt
          • sha1
          • sha256
          • sha512
          • formatdate
          • timeadd
          • base64decode
          • base64encode
          • csvdecode
          • jsondecode
          • jsonencode
          • urlencode
          • yamldecode
          • yamlencode
          • abspath
          • basename
          • dirname
          • file
          • fileexists
          • fileset
          • pathexpand
          • cidrhost
          • cidrnetmask
          • cidrsubnet
          • cidrsubnets
          • abs
          • ceil
          • floor
          • log
          • max
          • min
          • parseint
          • pow
          • signum
          • chomp
          • format
          • formatlist
          • indent
          • join
          • lower
          • regex_replace
          • replace
          • split
          • strrev
          • substr
          • title
          • trim
          • trimprefix
          • trimspace
          • trimsuffix
          • upper
          • uuidv4
          • uuidv5
      • Locals
      • Syntax
      • Variables
    • artifact
    • affinity
    • check_restart
    • connect
    • constraint
    • csi_plugin
    • device
    • dispatch_payload
    • env
    • ephemeral_disk
    • expose
    • gateway
    • group
    • job
    • lifecycle
    • logs
    • meta
    • migrate
    • multiregion
    • network
    • parameterized
    • periodic
    • proxy
    • reschedule
    • resources
    • restart
    • scaling
    • service
    • sidecar_service
    • sidecar_task
    • spread
    • task
    • template
    • update
    • upstreams
    • vault
    • volume
    • volume_mount
    • Overview
    • Docker
    • Isolated Fork/Exec
    • Java
    • Podman
    • QEMU
    • Raw Fork/Exec
      • Overview
      • containerd
      • Firecracker driver
      • Jailtask driver
      • Lightrun
      • LXC
      • Pot
      • Rkt Deprecated
      • Rookout
      • Singularity
      • systemd-nspawn
      • Windows IIS
      • Overview
      • ECS
    • Overview
      • Overview
      • Nvidia
      • USB Beta
  • Schedulers
    • Overview
    • Runtime Environment
    • Variable Interpolation
    • Overview
      • Overview
      • apm
      • dynamic_application_sizing
      • http
      • nomad
      • policy
      • policy_eval
      • source
      • strategy
      • target
      • telemetry
    • API
    • CLI
    • Policy
    • Telemetry
      • Overview
        • Overview
        • Datadog
        • Nomad API
        • Prometheus
        • Overview
        • Dynamic Application Sizing Average
        • Dynamic Application Sizing Max
        • Dynamic Application Sizing Percentile
        • Fixed Value
        • Pass-Through
        • Target Value
        • Threshold
        • Overview
        • Amazon Web Services Autoscaling Group
        • Azure Virtual Machine Scale Set
        • Dynamic Application Sizing
        • Google Cloud Engine Managed Instance Group
        • Nomad Task Group
      • Community
      • Overview
      • Checks
      • Node Selector Strategy
        • Overview
        • Base
        • APM
        • Strategy
        • Target
    • Overview
    • Operating Nomad Agents
    • Monitoring Nomad
    • Metrics Reference
    • Cluster Management
    • Transport Security
    • Access Control

    • Overview
    • Alternative to Kubernetes
    • Supplement to Kubernetes
  • Nomad Ecosystem
  • Nomad Partnerships
  • Who Uses Nomad
    • Overview
      • Overview
      • FAQ
  • FAQ
Type '/' to Search

»lifecycle Stanza

Placementjob -> group -> task -> lifecycle

The lifecycle stanza is used to express task dependencies in Nomad by configuring when a task is run within the lifecycle of a task group.

Main tasks are tasks that do not have a lifecycle stanza. Lifecycle task hooks specify when other tasks are run in relation to the main tasks. There are three different lifecycle hooks, indicating when a task is started:

  • prestart tasks are started immediately
  • poststart tasks are started after the main tasks are running
  • poststop tasks are started after the main tasks are dead

Tasks can be run with an additional parameter indicating whether they are ephemeral tasks or "sidecar" tasks that are expected to run for the duration of the main tasks. The absence of the sidecar flag indicates that the task is ephemeral and should not be restarted if it completes successfully.

Learn more about Nomad's task dependencies on the HashiCorp Learn website.

»lifecycle Parameters

  • hook (string: <required>) - Specifies when a task should be run within the lifecycle of a group. The following hooks are available:

    • prestart - Will be started immediately. The main tasks will not start until all prestart tasks with sidecar = false have completed successfully.
    • poststart - Will be started once all main tasks are running.
    • poststop - Will be started once all main tasks have stopped successfully or exhausted their failure retries.
  • sidecar (bool: false) - Controls whether a task is ephemeral or long-lived within the task group. If a lifecycle task is ephemeral (sidecar = false), the task will not be restarted after it completes successfully. If a lifecycle task is long-lived (sidecar = true) and terminates, it will be restarted as long as the allocation is running.

»Lifecycle Examples

The following include examples of archetypal lifecycle patterns.

»Init Task Pattern

Init tasks are useful for performing initialization steps that can't be more easily accomplished using template or artifact, like waiting on other services or performing complex initialization.

In the following example, the init task will block the main task from starting until the upstream database service is listening on the expected port:

  task "wait-for-db" {
    lifecycle {
      hook = "prestart"
      sidecar = false
    }

    driver = "exec"
    config {
      command = "sh"
      args = ["-c", "while ! nc -z db.service.local.consul 8080; do sleep 1; done"]
    }
  }

  task "main-app" {
    ...
  }
  task "wait-for-db" {
    lifecycle {
      hook = "prestart"
      sidecar = false
    }

    driver = "exec"
    config {
      command = "sh"
      args = ["-c", "while ! nc -z db.service.local.consul 8080; do sleep 1; done"]
    }
  }

  task "main-app" {
    ...
  }

»Companion Sidecar Pattern

Companion or sidecar tasks run alongside the main task to perform an auxiliary task. Common examples include proxies and log shippers. These tasks benefit from running in the same task group because of tighter filesystem and networking coupling.

  task "fluentd" {
    lifecycle {
      hook = "poststart"
      sidecar = true
    }

    driver = "docker"
    config {
      image = "fluentd/fluentd"
    }

    template {
      destination = "local/fluentd.conf"
      data = ...
    }
  }

  task "main-app" {
    ...
  }
  task "fluentd" {
    lifecycle {
      hook = "poststart"
      sidecar = true
    }

    driver = "docker"
    config {
      image = "fluentd/fluentd"
    }

    template {
      destination = "local/fluentd.conf"
      data = ...
    }
  }

  task "main-app" {
    ...
  }

»Cleanup Task Pattern

Poststop tasks run after the main tasks have stopped. They are useful for performing post-processing that isn't available in the main tasks or for recovering from failures in the main tasks.

The example below shows a chatbot which posts a notification when the main tasks have stopped:

  task "main-app" {
    ...
  }

  task "announce" {
    lifecycle {
      hook = "poststop"
    }

    driver = "docker"
    config {
      image = "alpine/httpie"
      command = "http"
      args = [
        "POST",
        "https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX",
        "text='All done!'"
      ]
    }
  }
  task "main-app" {
    ...
  }

  task "announce" {
    lifecycle {
      hook = "poststop"
    }

    driver = "docker"
    config {
      image = "alpine/httpie"
      command = "http"
      args = [
        "POST",
        "https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX",
        "text='All done!'"
      ]
    }
  }
github logoEdit this page
DocsAPIResourcesPrivacySecurityPress KitConsent Manager