lifecycle Block
Placement | job -> group -> task -> lifecycle |
The lifecycle
block 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
block. 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.
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 allprestart
tasks withsidecar = 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:
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.
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: