n8n 实战工作流模板:GitHub→飞书通知、定时爬虫→数据库、Webhook→多渠道推送
n8n 是一款开源的工作流自动化平台,以可视化节点编排和丰富的集成能力著称。相比 Zapier 或 Make,自托管 n8n 没有执行次数限制,数据完全保留在自己的服务器上。本文跳过基础部署环节,直接深入三个完整的实战工作流配置案例,并提供可直接导入的 JSON 配置,帮助你快速落地自动化业务流程。
服务器配置
n8n 在处理复杂工作流时需要足够的内存来维持 Node.js 运行时。推荐使用 雨云服务器 rainyun-com ,注册填优惠码 2026off 领 5 折优惠券,选择 2 核 4GB 内存机型,可同时运行多个活跃工作流而不出现内存溢出。
- 推荐机型:2 核 4GB / SSD 60GB
- 操作系统:Ubuntu 22.04 LTS
- 建议配置:2 核 4GB 已可流畅运行 50+ 个工作流,若涉及大量数据处理建议升级到 4 核 8GB
数据库方面,生产环境强烈建议将 n8n 默认的 SQLite 切换到 PostgreSQL,以提升并发执行的稳定性。
前置准备
Docker Compose 部署 n8n + PostgreSQL
yaml
# /opt/n8n/docker-compose.yml
version: "3.8"
services:
postgres:
image: postgres:16-alpine
container_name: n8n-postgres
restart: unless-stopped
volumes:
- /opt/n8n/pgdata:/var/lib/postgresql/data
environment:
POSTGRES_DB: n8n
POSTGRES_USER: n8n
POSTGRES_PASSWORD: "${PG_PASSWORD}"
n8n:
image: n8nio/n8n:latest
container_name: n8n
restart: unless-stopped
ports:
- "127.0.0.1:5678:5678"
volumes:
- /opt/n8n/data:/home/node/.n8n
environment:
DB_TYPE: postgresdb
DB_POSTGRESDB_HOST: postgres
DB_POSTGRESDB_PORT: 5432
DB_POSTGRESDB_DATABASE: n8n
DB_POSTGRESDB_USER: n8n
DB_POSTGRESDB_PASSWORD: "${PG_PASSWORD}"
N8N_HOST: "n8n.yourdomain.com"
N8N_PORT: 5678
N8N_PROTOCOL: https
WEBHOOK_URL: "https://n8n.yourdomain.com/"
# 加密密钥(首次设置后不能更改)
N8N_ENCRYPTION_KEY: "${N8N_ENCRYPTION_KEY}"
# 时区
GENERIC_TIMEZONE: Asia/Shanghai
TZ: Asia/Shanghai
depends_on:
postgres:
condition: service_healthy
bash
# 生成加密密钥
openssl rand -hex 32
# 启动服务
cd /opt/n8n && docker compose up -d
配置步骤
工作流一:GitHub Push → 飞书群通知
场景:代码仓库有新的 Push 或 Pull Request 时,自动向飞书群发送通知卡片,包含提交者、分支、提交信息和对比链接。
节点结构 :Webhook (GitHub) → IF(过滤分支) → HTTP Request(飞书 Webhook)
完整 JSON 配置(可在 n8n 中直接导入):
json
{
"name": "GitHub Push 通知飞书",
"nodes": [
{
"parameters": {
"httpMethod": "POST",
"path": "github-webhook",
"responseMode": "onReceived",
"responseData": "firstEntryJson"
},
"name": "GitHub Webhook",
"type": "n8n-nodes-base.webhook",
"position": [250, 300]
},
{
"parameters": {
"conditions": {
"string": [
{
"value1": "={{$json[\"ref\"]}}",
"operation": "contains",
"value2": "refs/heads/main"
}
]
}
},
"name": "过滤 main 分支",
"type": "n8n-nodes-base.if",
"position": [500, 300]
},
{
"parameters": {
"url": "https://open.feishu.cn/open-apis/bot/v2/hook/YOUR_FEISHU_HOOK_TOKEN",
"method": "POST",
"jsonParameters": true,
"bodyParametersJson": "={\n \"msg_type\": \"interactive\",\n \"card\": {\n \"elements\": [\n {\n \"tag\": \"div\",\n \"text\": {\n \"content\": \"**仓库**:{{$json[\\\"repository\\\"][\\\"full_name\\\"]}}\\n**分支**:{{$json[\\\"ref\\\"].replace('refs/heads/', '')}}\\n**提交者**:{{$json[\\\"pusher\\\"][\\\"name\\\"]}}\\n**消息**:{{$json[\\\"head_commit\\\"][\\\"message\\\"]}}\",\n \"tag\": \"lark_md\"\n }\n },\n {\n \"tag\": \"action\",\n \"actions\": [\n {\n \"tag\": \"button\",\n \"text\": {\"content\": \"查看对比\", \"tag\": \"plain_text\"},\n \"url\": \"={{$json[\\\"compare\\\"]}}\",\n \"type\": \"default\"\n }\n ]\n }\n ],\n \"header\": {\n \"template\": \"blue\",\n \"title\": {\"content\": \"🚀 新代码已推送\", \"tag\": \"plain_text\"}\n }\n }\n}"
},
"name": "发送飞书通知",
"type": "n8n-nodes-base.httpRequest",
"position": [750, 250]
}
],
"connections": {
"GitHub Webhook": {"main": [[{"node": "过滤 main 分支", "type": "main", "index": 0}]]},
"过滤 main 分支": {"main": [[{"node": "发送飞书通知", "type": "main", "index": 0}], []]}
}
}
GitHub 端配置:
- 打开仓库 → Settings → Webhooks → Add webhook
- Payload URL 填入:
https://n8n.yourdomain.com/webhook/github-webhook - Content type 选
application/json - 选择触发事件:
Push events+Pull requests
HTTP Request 节点关键参数说明:
url:飞书自定义机器人的 Webhook 地址method:POSTContent-Type:application/json- Body 中使用 n8n 表达式
={``{ }}动态填充 GitHub 事件数据
工作流二:定时爬虫 → 数据库存储
场景:每小时抓取指定网页的价格或文章列表,去重后存入 PostgreSQL 数据库,用于价格监控或内容聚合。
节点结构 :Cron(定时) → HTTP Request(抓取页面) → HTML Extract(提取数据) → IF(去重判断) → Postgres(写入数据库)
json
{
"name": "定时爬虫存库",
"nodes": [
{
"parameters": {
"rule": {
"interval": [{"field": "hours", "minutesInterval": 1}]
}
},
"name": "每小时触发",
"type": "n8n-nodes-base.scheduleTrigger",
"position": [250, 300]
},
{
"parameters": {
"url": "https://target-website.com/list",
"method": "GET",
"options": {
"timeout": 30000,
"redirect": {"redirect": {"maxRedirects": 5}},
"response": {"response": {"responseFormat": "text"}}
}
},
"name": "抓取页面",
"type": "n8n-nodes-base.httpRequest",
"position": [500, 300]
},
{
"parameters": {
"extractionValues": {
"values": [
{
"key": "title",
"cssSelector": ".article-title",
"returnValue": "text"
},
{
"key": "link",
"cssSelector": ".article-title a",
"returnValue": "attribute",
"attribute": "href"
},
{
"key": "price",
"cssSelector": ".price",
"returnValue": "text"
}
]
},
"options": {"returnArray": true}
},
"name": "提取数据",
"type": "n8n-nodes-base.htmlExtract",
"position": [750, 300]
},
{
"parameters": {
"operation": "executeQuery",
"query": "INSERT INTO crawled_items (title, link, price, crawled_at) VALUES ('{{$json[\"title\"]}}', '{{$json[\"link\"]}}', '{{$json[\"price\"]}}', NOW()) ON CONFLICT (link) DO UPDATE SET price = EXCLUDED.price, updated_at = NOW()"
},
"name": "写入 PostgreSQL",
"type": "n8n-nodes-base.postgres",
"position": [1000, 300]
}
]
}
Cron 调度配置说明:
| 调度规则 | Cron 表达式 | n8n 设置 |
|---|---|---|
| 每小时整点 | 0 * * * * |
interval: 1 hour |
| 每天上午 9 点 | 0 9 * * * |
scheduleTrigger |
| 工作日每 30 分钟 | */30 9-18 * * 1-5 |
自定义 Cron |
在 n8n 的 Schedule Trigger 节点中,可以直接输入 Cron 表达式或使用可视化选择器。
工作流三:Webhook → 多渠道推送(含错误处理)
场景:接受来自任意系统的 Webhook 告警,同时推送到飞书、企业微信、钉钉和邮件,并内置错误重试和错误日志节点。
节点结构 :Webhook → Switch(渠道路由) → [飞书 / 企业微信 / 钉钉 / 邮件] → Error Trigger(错误处理) → 发送错误日志
json
{
"name": "多渠道告警推送",
"nodes": [
{
"parameters": {
"httpMethod": "POST",
"path": "alert-push",
"responseMode": "onReceived"
},
"name": "接收告警",
"type": "n8n-nodes-base.webhook",
"position": [250, 300]
},
{
"parameters": {
"dataType": "string",
"value1": "={{$json[\"channel\"]}}",
"rules": {
"rules": [
{"value2": "feishu", "output": 0},
{"value2": "wecom", "output": 1},
{"value2": "dingtalk", "output": 2},
{"value2": "email", "output": 3}
]
},
"fallbackOutput": 0
},
"name": "渠道路由",
"type": "n8n-nodes-base.switch",
"position": [500, 300]
},
{
"parameters": {
"url": "https://open.feishu.cn/open-apis/bot/v2/hook/FEISHU_TOKEN",
"method": "POST",
"jsonParameters": true,
"bodyParametersJson": "={\"msg_type\":\"text\",\"content\":{\"text\":\"[告警] {{$json[\\\"title\\\"]}}\\n{{$json[\\\"message\\\"]}}\"}}"
},
"name": "推送飞书",
"type": "n8n-nodes-base.httpRequest",
"position": [750, 150]
},
{
"parameters": {
"url": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=WECOM_KEY",
"method": "POST",
"jsonParameters": true,
"bodyParametersJson": "={\"msgtype\":\"text\",\"text\":{\"content\":\"[告警] {{$json[\\\"title\\\"]}}\\n{{$json[\\\"message\\\"]}}\"}}"
},
"name": "推送企业微信",
"type": "n8n-nodes-base.httpRequest",
"position": [750, 300]
}
]
}
错误处理节点配置:
在 n8n 中,每个工作流都支持设置 Error Workflow。在工作流设置中指定错误工作流 ID,当任何节点执行失败时,n8n 会自动触发该错误工作流:
javascript
// 错误工作流中可用的数据结构
// $json.execution.id - 失败的执行 ID
// $json.execution.url - 执行详情链接
// $json.error.message - 错误信息
// $json.workflow.name - 工作流名称
核心功能
HTTP Request 节点进阶用法
HTTP Request 是 n8n 中最通用的节点,支持以下高级特性:
javascript
// 动态 URL(使用前一节点的输出)
URL: ={{ "https://api.example.com/users/" + $json["userId"] }}
// 认证头部
Headers: {
"Authorization": "Bearer {{ $credentials.apiToken }}",
"X-Custom-Header": "={{ $json["customValue"] }}"
}
// 分页处理(Pagination 设置)
Pagination Mode: Update a Parameter
Pagination Parameter: page
Max Pages: 10
进阶技巧
工作流版本管理
bash
# n8n 数据目录中包含工作流 JSON,可用 Git 管理
cd /opt/n8n/data
git init
git add workflows/
git commit -m "backup workflows $(date +%Y%m%d)"
环境变量在工作流中的引用
bash
# 在 docker-compose.yml 中定义
environment:
- FEISHU_WEBHOOK_URL=https://open.feishu.cn/open-apis/bot/v2/hook/YOUR_TOKEN
# 在节点中引用
URL: ={{ $env.FEISHU_WEBHOOK_URL }}
常见问题
Q:Webhook 节点收不到外部请求?
确认 WEBHOOK_URL 环境变量与实际域名一致,且 Nginx 已正确反向代理到 5678 端口。测试方法:curl -X POST https://n8n.yourdomain.com/webhook/test -d '{"test":1}'
Q:Cron 工作流时区不对?
确认 GENERIC_TIMEZONE=Asia/Shanghai 已正确设置,重启容器后生效。n8n 管理界面右上角也会显示当前服务器时区。
Q:HTTP Request 返回数据格式解析失败?
在节点的 Response 设置中,将 "Response Format" 改为 JSON,并勾选 "Split Into Items" 可将数组自动拆分为多条数据流。
Q:工作流执行历史占满磁盘?
在 n8n 设置中(N8N_EXECUTIONS_DATA_PRUNE=true,N8N_EXECUTIONS_DATA_MAX_AGE=336)开启自动清理,默认保留 14 天执行记录。
n8n 的强大之处在于一旦搭建好底座,后续添加新自动化场景几乎零边际成本。无论是对接内部系统还是第三方服务,可视化节点编排让非开发者也能快速上手。想要低延迟运行上述工作流,雨云服务器 rainyun-com 的 2 核 4GB 机型 是最佳起点,优惠码 2026off 享 5 折优惠,稳定运行数十个工作流不在话下。