解决Dify代码执行器网络报错:Failed to execute code

Source

问题现象

在本地部署Dify测试环境后,导入DSL应用文件并执行Workflow时,代码执行器模块出现以下网络异常提示:

Failed to execute code, which is likely a network issue, 
please check if the sandbox service is running. 
( Error: [Errno -2] Name or service not known )

img

排查过程

针对该错误进行了多维度排查:

  1. 网络配置验证:检查Docker容器网络模式(默认bridge),确认容器间通信正常
  2. 代理设置:尝试配置SOCKS5/HTTP代理(通过环境变量和Docker参数)
  3. DNS优化:修改Docker守护进程的daemon.json,添加公共DNS(如8.8.8.8)
  4. 超时调整:将代码执行超时阈值从默认5秒延长至30秒
  5. 日志追踪:最终在sandbox服务日志中发现关键线索:
Config file not found at xxxx/config.yaml

根本原因

Dify的沙箱服务(sandbox)需要config.yaml配置文件来初始化网络参数,但在Docker部署流程中,该文件未自动生成到挂载目录。

解决方案

步骤1:获取配置文件

访问GitHub仓库下载标准配置文件:

wget https://raw.githubusercontent.com/langgenius/dify/main/docker/volumes/sandbox/conf/config.yaml

步骤2:配置关键参数

建议重点关注以下配置项(根据环境调整):

app:
  port: 8194
  debug: True
  key: dify-sandbox
max_workers: 4
max_requests: 50
worker_timeout: 5
python_path: /usr/local/bin/python3
enable_network: True  # 必须开启网络访问权限
allowed_syscalls: # 安全策略白名单
proxy:
  socks5: ''
  http: ''    # 如需代理在此处配置
  https: ''

该配置文件定义了沙箱环境的运行时参数:

  • 网络访问策略(enable_network)
  • Python解释器路径(python_path)
  • 进程资源限制(max_workers/worker_timeout)
  • 系统调用白名单(allowed_syscalls)

当配置文件缺失时,sandbox服务会默认禁用网络功能,导致代码执行器无法建立网络连接。

步骤3:部署配置文件

将下载的配置文件放置到指定目录:

# 创建配置目录(如果不存在)
mkdir -p ./docker/volumes/sandbox/conf/

# 移动配置文件
mv config.yaml ./docker/volumes/sandbox/conf/

步骤4:重启服务

docker compose down
docker compose up -d

再次执行代码,正常运行:

img

参考