You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Docker SDK exec_run写入Docker容器内文件失败如何解决

问题原因
  • 你使用exec_run传入列表形式的命令时,默认不会启动shell环境解析命令语法,>属于shell专属的重定向操作符,没有shell环境的情况下,>会被当做普通字符串参数传给echo命令,最终只会把重定向符号和文件路径也打印到标准输出,不会执行写入文件的操作。
  • 原代码的字典定义存在语法错误,键a、b如果是字符串类型需要加引号,否则运行时会报变量未定义错误。
修正方案

你可以根据场景选择以下两种修复方式:

方案1:启用shell解析命令,适合内容简单无特殊字符的场景

将整条命令通过sh -c包裹,让shell解析重定向逻辑:

import json
import docker

client = docker.from_env()
# 修正字典键的引号问题
data = {"a":"1", "b":"2"}
data_string = json.dumps(data)
container_nodered = client.containers.get("my_container")
# 用sh -c包裹整条命令,同时做转义避免特殊字符破坏命令结构
container_nodered.exec_run(f"sh -c 'echo {json.dumps(data_string)} > /test.txt'")

方案2:直接通过Docker文件传输接口写入,无转义问题,稳定性更高

直接构造内存中的文件包写入容器,完全避免命令解析导致的各类问题:

import json
import docker
import tarfile
from io import BytesIO

client = docker.from_env()
data = {"a":"1", "b":"2"}
data_string = json.dumps(data)

# 构造内存tar包,包含要写入的文件
tar_stream = BytesIO()
with tarfile.open(fileobj=tar_stream, mode='w') as tar:
    tarinfo = tarfile.TarInfo(name='test.txt')
    tarinfo.size = len(data_string.encode('utf-8'))
    tar.addfile(tarinfo, BytesIO(data_string.encode('utf-8')))
tar_stream.seek(0)

container_nodered = client.containers.get("my_container")
# 写入容器根路径,自动生成/test.txt
container_nodered.put_archive(path='/', data=tar_stream)

内容的提问来源于stack exchange,提问作者CroatiaHR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 19:45:07