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

Airflow在Docker容器中无法找到本地文件的求助

问题分析与解决方案

核心问题是运行环境的工作目录不一致:本地执行脚本时,工作目录是脚本所在的文件夹;而Airflow在Docker容器内运行PythonOperator时,默认工作目录是Airflow的主目录(通常为/usr/local/airflow),导致相对路径./store_files_airflow/raw_store_transactions.csv无法指向正确的文件位置。

排查与解决步骤

1. 确认Airflow运行时的工作目录

先在check_file.py中添加当前工作目录的打印,明确Airflow的执行路径:

import os

def check_file_exists():
    # 打印当前工作目录
    print(f"Current working directory: {os.getcwd()}\n")
    
    file_path = "./store_files_airflow/raw_store_transactions.csv"
    if os.path.isfile(file_path):
        print(f"{file_path} exists!\n")
    else:
        print(f"{file_path} does not exist.\n")
    return os.path.isfile(file_path)

执行DAG后查看日志,就能清楚Airflow实际在哪个目录下寻找文件。

2. 改用绝对路径定位文件

有两种可靠的绝对路径写法:

方式一:基于脚本所在目录拼接路径

这种方式不依赖固定的容器路径,兼容性更强:

import os

def check_file_exists():
    # 获取当前脚本的绝对目录
    script_dir = os.path.dirname(os.path.abspath(__file__))
    # 拼接目标文件的绝对路径
    file_path = os.path.join(script_dir, "store_files_airflow", "raw_store_transactions.csv")
    
    if os.path.isfile(file_path):
        print(f"{file_path} exists!\n")
    else:
        print(f"{file_path} does not exist.\n")
    return os.path.isfile(file_path)

方式二:直接使用容器内的固定绝对路径

如果你明确知道文件在Docker容器内的挂载位置,比如/usr/local/airflow/store_files_airflow/raw_store_transactions.csv,可以直接写死路径:

import os

def check_file_exists():
    file_path = "/usr/local/airflow/store_files_airflow/raw_store_transactions.csv"
    
    if os.path.isfile(file_path):
        print(f"{file_path} exists!\n")
    else:
        print(f"{file_path} does not exist.\n")
    return os.path.isfile(file_path)

3. 验证Docker目录挂载配置

确保本地的store_files_airflow目录已经正确挂载到Airflow容器内的对应路径。如果使用docker-compose.yml,检查挂载配置是否类似:

services:
  airflow-webserver:
    volumes:
      # 本地目录:容器内目录
      - ./store_files_airflow:/usr/local/airflow/store_files_airflow
      # 其他必要挂载...

M1 Mac下Docker的路径挂载需注意本地路径的正确性,避免因系统架构差异导致挂载失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 02:22:56