跳至内容

任务运行器#

任务执行器是一种通用机制,用于以安全高效的方式执行任务。它们被用来在Code节点中执行用户提供的JavaScript代码。

本文档描述了任务运行器的工作原理及其配置方法。

工作原理#

任务运行器功能由三个组件组成:任务运行器、任务代理和任务请求者。

Task runner overview

任务执行器通过WebSocket连接与任务代理建立连接。任务请求者向代理提交任务请求,由可用的任务执行器接收并执行。

执行器运行任务并将结果提交给任务请求方。任务代理协调执行器与请求方之间的通信。

n8n实例(主节点和工作节点)充当代理。在这种情况下,代码节点是任务请求者。

任务运行器模式#

您可以在两种不同的模式下使用任务运行器:内部模式和外部模式。

内部模式#

在内部模式下,n8n实例将任务运行器作为子进程启动。n8n进程监控并管理任务运行器的生命周期。任务运行器进程与n8n共享相同的uidgid

外部模式#

在外部模式下,外部编排器(例如Kubernetes)会启动任务运行器而非n8n。通常这意味着您需要将任务运行器配置为作为n8n旁边的边车容器运行。

Task runner deployed as a side-car container

在此模式下,编排器会监控并管理任务运行器容器的生命周期。任务运行器与n8n实例完全隔离。

在使用队列模式时,每个n8n容器(主容器和工作容器)都需要拥有自己的任务运行器。

设置外部模式#

使用以下详细信息配置外部模式下的任务运行器

配置外部模式下的n8n实例#

您可以通过设置以下环境变量来配置n8n使用外部任务运行器:

环境变量 描述
N8N_RUNNERS_ENABLED=true Enables task runners.
N8N_RUNNERS_MODE=external Use task runners in external mode.
N8N_RUNNERS_AUTH_TOKEN=<random secure shared secret> A shared secret task runners use to connect to the broker.
N8N_RUNNERS_BROKER_LISTEN_ADDRESS=0.0.0.0 By default, the task broker only listens to localhost. When using multiple containers (for example, with Docker Compose), it needs to be able to accept external connections.

完整的环境变量列表请参阅任务运行器环境变量

配置外部模式下的任务运行器#

任务运行器已内置于n8n Docker镜像中。该Docker镜像还包含任务运行器启动程序。

启动器可以按需启动运行器,这意味着在没有工作需要时内存使用率较低,但在冷启动时会有短暂延迟(几百毫秒)。启动器还会监控运行器,并在出现无限循环或其他问题时重新启动它。

通过设置以下属性从n8n Docker镜像运行任务运行器容器:

配置 描述
command ["/usr/local/bin/task-runner-launcher", "javascript"]
livenessProbe GET /healthz, port 5680

为容器设置以下环境变量,根据您的需求进行调整:

环境变量 描述
N8N_RUNNERS_AUTH_TOKEN=<random secure shared secret> The shared secret the task runner uses to connect to the broker.
N8N_RUNNERS_MAX_CONCURRENCY=5 The number of concurrent tasks the runner can execute.
N8N_RUNNERS_TASK_BROKER_URI=localhost:5679 The address of the task broker server within the n8n instance.
N8N_RUNNERS_AUTO_SHUTDOWN_TIMEOUT=15 Number of seconds of inactivity to wait before shutting down the task runner process. The launcher will automatically start the runner again when there are new tasks to execute. Set to 0 to disable automatic shutdown.
NODE_OPTIONS=--max-old-space-size=<limit> The memory limit for the task runner Node.js process. This should be lower than the limit for container so that the runner runs out of memory before the container. That way, the launcher is able to monitor the runner.
GENERIC_TIMEZONE The same default timezone as configured for the n8n instance.

完整的环境变量列表请参阅任务运行器环境变量

优云智算