DEBUG.WIKI
IPPeak:从目标地区访问网页,住宅代理、SEO 监测、广告验证
阿里云;从建站到云上业务;云服务器 · 数据库 · 对象存储;查看产品 →
搬瓦工;先看线路,再选 VPS;CN2 GIA · 对应线路套餐;查看线路 →

解决 Apache Spark 报错 Executor lost exit code 137 故障

分析 Apache Spark 任务报 Executor lost 及 exit code 137 内存溢出诱因,详解 off-heap 堆外内存与数据倾斜调优方案。

问题现象

在 Kubernetes 或 YARN 上提交 Apache Spark 分布式计算任务时,Task 频繁失败重试,Driver 日志中输出:

2026-11-15 09:15:30 ERROR TaskSchedulerImpl: Lost executor 4 on 10.0.0.15: Container killed by YARN for exceeding memory limits. 14.2 GB of 14.0 GB physical memory used. Consider boosting spark.yarn.executor.memoryOverhead.

在 Kubernetes 部署架构下报错表现为:

ExecutorLostFailure (executor 3 exited caused by one of the running tasks) Reason: Container marked as failed: executor-3 (exit code: 137)

触发根因

  1. 堆外内存(Off-Heap / Overhead Memory)超出配额:Spark 默认分配给容器额外的堆外开销(spark.executor.memoryOverhead)仅为 executor 内存的 10%(最小 384MB)。当使用 PySpark、Pandas UDF、JNI 或 Shuffle 缓冲区溢出时,物理内存触顶被操作系统 OOM Killer 杀掉(128 + 9 = 137)。
  2. 数据倾斜(Data Skew)导致单个分区超大:大量数据集中在某一个 Key 上,单个 Executor 处理时内存打爆。
  3. 调用了 collect() 将全量数据拉回。

诊断排查步骤

  1. 在 Kubernetes 检查 Executor Pod 的销毁原因:
kubectl describe pod <executor-pod-name> -n spark

确认 Last State: Terminated,Reason: OOMKilled,Exit Code: 137。

  1. 在 Spark UI 的 Stages 页面观察任务执行时长的分布直方图,检查是否存在少数 Task 耗时与 Shuffle Read 远超中位数的倾斜情况。

解决步骤与操作命令

步骤一:调大堆外开销内存(spark.executor.memoryOverhead)

特别是在使用 PySpark 或 Arrow 序列化时,将开销内存提高到 20%~40%:

spark-submit   --master k8s://https://10.0.0.1:6443   --conf spark.executor.memory=8g   --conf spark.executor.memoryOverhead=3g   --conf spark.kubernetes.executor.request.cores=2   app.py

步骤二:开启自适应查询执行(AQE)解决数据倾斜

在 Spark 3.0+ 中启用自适应特性,自动合并微小分区并拆分倾斜分区:

--conf spark.sql.adaptive.enabled=true --conf spark.sql.adaptive.skewJoin.enabled=true --conf spark.sql.adaptive.coalescePartitions.enabled=true

步骤三:针对 Shuffle 溢出开启溢盘压缩

--conf spark.shuffle.spill.compress=true --conf spark.shuffle.compress=true

验证方法

重新提交 Spark 计算作业: 在 Spark UI 查看 Executing Tasks 与 Executors 列表,所有 Executor 容器稳定运行直至 Stage 全部计算完成,无任何 Exit Code 137 退出重试。