代码之家  ›  专栏  ›  技术社区  ›  Spoofa

Docker python:无法打开文件“/app/main.py”:[Erno 2]没有这样的文件或目录script_execution_service退出,代码为2

  •  0
  • Spoofa  · 技术社区  · 1 年前

    结构如下:

    ├── data_storage_service
    │   ├── db
    │   ├── Dockerfile
    │   └── initial-db.sqlite
    ├── docker-compose.yml
    └── script_execution_service
        ├── app
        ├── Dockerfile
        ├── main.py
        └── requirements.txt  
    

    1) data_storage_service中的Dockerfile是:“

    
    FROM alpine:latest
    
    RUN apk --no-cache add sqlite
    
    WORKDIR /db
    
    COPY initial-db.sqlite /db/
    
    CMD ["tail", "-f", "/dev/null"]
    
    
    1. initial-db.sqlite仍然为空

    2. docker-compose.yml如下所示:

    version: '3.8'
    
    services:
      data_storage_service:
        build:
          context: ./data_storage_service
        container_name: data_storage_service
        volumes:
          - ./data_storage_service/db:/db
      script_execution_service:
        build:
          context: ./script_execution_service
        container_name: script_execution_service
        depends_on:
          - data_storage_service
        volumes:
          - ./script_execution_service/app:/app
        environment:
          - DB_PATH=/db/initial-db.sqlite
    
    1. script_execution_service中的Dockerfile:
    FROM python:3.10
    
    WORKDIR /app
    
    COPY requirements.txt .
    RUN pip install --no-cache-dir -r requirements.txt
    
    COPY . .
    CMD ["python", "main.py"]
    
    1. main.py如下所示:
    import os
    import sqlite3
    
    def fetch_data_from_db(db_path, table_name):
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        cursor.execute(f"SELECT * FROM {table_name}")
        rows = cursor.fetchall()
        conn.close()
        return rows
    
    def main():
        db_path = os.environ.get('DB_PATH')
        ventes = fetch_data_from_db(db_path, 'ventes')
        print(ventes)
    
    if __name__ == '__main__':
        main()
    

    当我执行docker compose up时,我会出现以下错误:

    script_execution_service  | python: can't open file '/app/main.py': [Errno 2] No such file or directory
    

    有人能帮我吗,我是新手。谢谢

    1 回复  |  直到 1 年前
        1
  •  1
  •   David Maze    1 年前

    在Compose文件中,您正在覆盖图像的 /app 目录及其所有代码。你通常不想这样做,因为这会导致不可预测的结果。

    您可以将数据库位置设置为一个独立的目录,这通常是一种很好的做法。将主机目录装载到容器中时,需要确保将其装载到预期数据所在的目录中。

    version: '3.8'
    services:
      script_execution_service:
        build: ./script_execution_service
        volumes:
          - ./script_execution_service/db:/db
          #                               ^^^ make this path match DB_PATH below
        environment:
          - DB_PATH=/db/initial-db.sqlite