在 jenkins pipeline 中用 timeout 步骤控制部署阶段最大耗时,需置于 steps 内、单位用单引号大写(如 'minutes'),超时后中止子进程并标记为 aborted;可结合 try/catch 清理资源,或嵌套 retry 实现幂等重试。

在 Linux 环境下使用 Jenkins Pipeline 控制特定部署阶段的最大耗时,核心是用 timeout 步骤包裹该 stage 的执行逻辑。它不是系统级超时命令,而是 Jenkins 原生的流水线控制指令,作用于 Jenkins agent 上运行的 shell 或脚本任务。
明确 timeout 的作用范围
timeout 只对它包裹的代码块生效,不影响其他 stage 或全局流程。它会在超时后主动中止当前 block 内所有正在运行的子进程(如 sh 启动的脚本),并标记该 stage 为 aborted,不会自动重试或跳过后续 stage —— 行为由你定义。
- 必须写在
steps块内,不能直接放在 stage 标签层级 - 单位必须用单引号包围且全大写,例如
'MINUTES',写成minutes或"minutes"会报错 - 超时触发后抛出异常,若需自定义处理(比如记录日志、清理资源),应配合
try/catch
部署阶段加 timeout 的标准写法
以实际部署脚本 deploy.sh 为例,限制其最多运行 12 分钟:
stage('Deploy to Prod') {
steps {
timeout(time: 12, unit: 'MINUTES') {
sh './deploy.sh --env=production'
}
}
}
如果 deploy.sh 在 12 分钟内未退出,Jenkins 会终止它,并在构建日志中显示 Cancelling nested steps due to timeout。注意:该脚本本身需具备可中断性(比如不忽略 SIGTERM),否则可能残留进程。
结合重试与超时避免误判
网络抖动或临时资源争用可能导致部署脚本偶发失败。可嵌套 retry,但总耗时仍受外层 timeout 约束:
stage('Deploy with Retry') {
steps {
timeout(time: 8, unit: 'MINUTES') {
retry(3) {
sh './deploy.sh --retry-safe'
}
}
}
}
- 最多重试 3 次,每次失败后立即重试(无等待)
- 从第一次执行开始计时,8 分钟内未成功则整体失败
- 确保
deploy.sh是幂等的,重复执行不会引发数据异常
超时后做必要清理(推荐)
单纯中断可能留下锁文件、临时容器或未关闭连接。用 try/catch 捕获 timeout 异常,执行清理动作:
stage('Safe Deploy') {
steps {
script {
try {
timeout(time: 10, unit: 'MINUTES') {
sh 'docker-compose -f prod.yml up -d'
sh 'curl -f http://localhost:8080/health || exit 1'
}
} catch (Exception e) {
echo "Deployment timed out or failed: ${e.message}"
sh 'docker-compose -f prod.yml down || true' // 确保清理
error "Deploy stage aborted after timeout"
}
}
}
}
这样既防止阻塞流水线,又避免环境残留影响下次构建。











