Airflow2.1.3升级后DockerOperator替换volumes为mounts报错如何解决
问题原因及修复方案
问题根因
- 你将
volumes参数直接替换为mounts后仍报错的核心原因是:新版本DockerOperator的mounts参数不支持旧版本volumes所用的冒号分隔字符串格式,必须传入结构化的Mount对象列表 - 报错中的
cannot unmarshal string into Go struct field HostConfig.HostConfig.Mounts of type mount.Mount,就是Docker服务端收到字符串类型的挂载配置后,无法解析为标准Mount结构体导致的。
修复方案
两种可选方案,按需选择即可:
方案1:使用标准Mount对象(推荐)
- 先导入Docker SDK的Mount类:
from docker.types import Mount
- 将原字符串列表替换为Mount实例列表,修改后的DockerOperator代码如下:
t_docker = DockerOperator( task_id='t_docker', image='customimage:latest', container_name='custom_1', api_version='auto', auto_remove=True, mounts=[ Mount(source="/home/airflow/scripts", target="/opt/airflow/scripts", type="bind"), Mount(source="/home/airflow/data", target="/opt/airflow/data", type="bind") ], docker_url='unix://var/run/docker.sock', network_mode='bridge', dag=dag )
如果需要设置只读挂载,在Mount实例中添加read_only=True参数即可。
方案2:使用兼容工具方法适配旧字符串写法
如果不想修改原有挂载配置的字符串格式,可以用Airflow提供的兼容转换方法:
- 导入转换工具:
from airflow.providers.docker.operators.docker import build_mounts_from_strings
- 直接将原字符串列表传入转换方法即可:
t_docker = DockerOperator( task_id='t_docker', image='customimage:latest', container_name='custom_1', api_version='auto', auto_remove=True, mounts=build_mounts_from_strings(['/home/airflow/scripts:/opt/airflow/scripts','/home/airflow/data:/opt/airflow/data']), docker_url='unix://var/run/docker.sock', network_mode='bridge', dag=dag )
内容的提问来源于stack exchange,提问作者Bart
相关产品推荐
相关产品推荐

