【发布时间】:2022-07-21 19:29:09
【问题描述】:
我的项目结构如下:
.
├── my_script.Dockerfile
├── README.rst
├── log
│ └── my_script.log
├── pickles
├── requirements.txt
├── requirements_my_script.txt
├── src
│ ├── __init__.py
│ ├── __pycache__
│ ├── main.py
│ ├── modules
│ │ ├── __init__.py
│ │ └── module.py
│ ├── other_scripts
│ │ └── my_script.py
│ └── utils
│ ├── __init__.py
│ ├── __pycache__
│ └── logging_utils.py
my_script.Dockerfile如下:
# syntax=docker/dockerfile:1
FROM python:3.10-slim-buster
WORKDIR /src
COPY requirements_my_script.txt requirements_my_script.txt
RUN pip3 install -r requirements_my_script.txt
COPY src/. .
CMD ["python3", "other_scripts/my_script.py"]
my_script.py:
import logging
from src.utils.logging_utils import start_logger
def main(logger):
# some code here
logger.info('done')
sleep(120)
if __name__=='__main__':
logger = start_logger('my_script.log')
try:
logger.info('Starting..')
main(logger)
except Exception as e:
logger.critical('Crashed with error: {}'.format(e))
还有 logging_utils.py:
import os
import logging
from logging.handlers import RotatingFileHandler
def start_logger(filename, level='INFO'): # INFO or DEBUG
# # LOGGING
log_folder = os.path.join(os.path.expanduser('~'), 'project_folder_name', 'log')
if not os.path.exists(log_folder):
os.makedirs(log_folder)
log_filename = filename
logger = logging.getLogger()
logFormatter = logging.Formatter(fmt='%(asctime)s :: %(levelname)s - %(message)s')
if level == 'DEBUG':
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
# add a rotating handler
handler = RotatingFileHandler(os.path.join(log_folder, log_filename), maxBytes=1000000, backupCount=1)
handler.setFormatter(logFormatter)
logger.addHandler(handler)
return logger
这在我的机器上完美运行,但是当我构建 docker 并尝试运行它时,我收到以下错误:
from src.utils.logging_utils import start_logger
ModuleNotFoundError: No module named 'src'
我在 dockerfile 中尝试了几种不同的 COPY 语句,但均未成功。
谁能告诉我我做错了什么?
【问题讨论】:
-
您在
my_script.py文件中尝试过from utils.logging_utils import start_logger吗? -
在我的本地机器中已经失败:from utils.logging_utils import start_logger ModuleNotFoundError: No module named 'utils'
-
我认为这是因为你在 DockerFile 中的
WORKDIR。您应该更改它或复制src目录,因为您只复制 src 内容。不是那个目录 -
将 dockerfile 更改为:``` FROM python:3.10-slim-buster WORKDIR /app COPY requirements_my_script.txt requirements_my_script.txt RUN pip3 install -r requirements_my_script.txt COPY src/ src/ CMD [" python3", "src/other_scripts/my_script.py"] ``` 但我得到同样的错误 (ModuleNotFoundError: No module named 'src')
标签: python docker python-module