我正在尝试在启用了调试的 Docker 容器中运行 Flask 服务器,以便我可以在开发过程中热重载并尝试更改。不幸的是,即使我已经验证文件已从容器内更改,热重载也未检测到更改。我的设置如下:
主机目录结构
|
|- Src
| |- app.py
|
|- docker-compose.yaml
|- Dockerfile
|- requirements.txt
需求.txt
flask
Dockerfile
FROM python:3.11-slim
ENV DEBUG_COLOR=true
ENV PYTHONPATH=.
RUN mkdir /usr/local/app
WORKDIR /usr/local/app
COPY requirements.txt /usr/local/app
RUN pip install -r requirements.txt
CMD ["python", "app.py"]
docker-compose.yaml
services:
test:
build:
dockerfile: ./Dockerfile
context: .
image: test:latest
environment:
- FLASK_DEBUG=1
ports: ['3000:3000']
volumes: [
'./src:/usr/local/app'
]
command:
python app.py
app.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
print('GET /, was called.')
return 'Hello world.'
if __name__ == "__main__":
app.run(host = '0.0.0.0', port = '3000')
我可以使用
docker compose up
从命令行启动此操作,所有内容都会按预期构建和运行,从而产生输出:
Attaching to test-1
test-1 | * Serving Flask app 'app'
test-1 | * Debug mode: on
test-1 | WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
test-1 | * Running on all addresses (0.0.0.0)
test-1 | * Running on http://127.0.0.1:3000
test-1 | * Running on http://172.18.0.2:3000
test-1 | Press CTRL+C to quit
test-1 | * Restarting with stat
test-1 | * Debugger is active!
test-1 | * Debugger PIN: 582-087-710
从中我可以看到调试器正在运行,并且应该使用 stat 重新启动。然后我可以访问 http://127.0.0.1:3000 提供的页面,它会提供预期的
Hello world!
。我还可以附加到正在运行的容器并使用 app.py
检查 cat app.py
的内容。
如果我然后在主机上启动编辑器并更改
app.py
的内容,例如将返回的消息更改为:
return 'Hello test world.'
我希望调试器能够检测到更改并重新加载,但它不会这样做。我可以查看容器中
app.py
的内容,我可以看到代码已更改,但访问该 URL 我仍然得到服务 Hello world!
。
非常欢迎对我在这里缺少的步骤提出任何建议!
根据您的示例,我将安装路径从
/usr/local/app
更改为/project
,并设置debug=True
。然后 Flask 能够检测到更改并再次正确热重载。
app.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
print('GET /, was called.')
return 'Hello world.'
if __name__ == "__main__":
app.run(host = '0.0.0.0', port = '3000', debug=True)
Dockerfile
FROM python:3.11-slim
ENV DEBUG_COLOR=true
ENV PYTHONPATH=.
#RUN mkdir /usr/local/app
WORKDIR /project
COPY requirements.txt /project
RUN pip install -r requirements.txt
# Declare it on either the `docker-compose.yml` or `Dockerfile`, you don't need both.
# CMD ["python", "app.py"]
docker-compose.yml
services:
test:
build:
dockerfile: ./Dockerfile
context: .
image: test:latest
# You're not using command like `flask run` to start the project, so it's not necessary either.
#environment:
# - FLASK_DEBUG=1
ports: ['3000:3000']
volumes: [
'./src:/project'
]
command:
python app.py
完成上述修改后,重建并启动项目。
$ docker compose up --build
这很奇怪。除非我将挂载路径从
/usr/local/app
更改为/project
(这可能与系统路径或Flask的看门狗有关),否则即使设置debug=True
或使用docker compose --watch
仍然无法进行热重载。
/usr/local
目录通常用于系统级安装,在 Docker 容器中安装卷时,文件系统事件可能无法正确传播。