我在 Flask 中實作了一個基本的 REST API。我想嘗試使用 Docker 對其進行容器化。我對 Docker 完全陌生,但根據我在各種論壇上的了解,這就是我設定的。
Dockerfile
FROM python:3.8-alpine
WORKDIR /myapplication
COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt
COPY . .
ENV FLASK_APP="app.py"
CMD ["python3", "-m" , "flask", "run"]
要求.txt
Flask==2.0.2
然后我去終端,然后運行
$ docker build -t myapp:latest .
構建成功,我可以看到my appDocker 桌面應用程式中列出了
然后我跑
$ docker run --rm -it -p 8080:8080 myapp:latest
* Serving Flask app 'app.py' (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL C to quit)
Docker 桌面顯示myapp正在使用中。
到目前為止,一切都很好。但這是我開始遇到問題的地方。
我也在使用 Postman 進行 API 路由測驗。如果我要在 Docker 之外運行應用程式,并且我去127.0.0.1:5000/data或我的任何其他路線,我會得到很好的回應。但是隨著 Docker 構建運行,我不再能夠訪問此路由或任何其他路由。
I have tried endless combinations: 127.0.0.1:5000, 127.0.0.1:8080, localhost, localhost:5000, localhost:8080, to no avail.
The only one that gives me ANY response is 127.0.0.1:5000. The response I do get is a 403 Forbidden, with Postman saying "The request was a legal request, but the server is refusing to respond to it."
For what its worth, I am running this on a new M1 Pro MacBook. I know the new Macs are touchy with permissioning, so I wouldn't be surprised if permissions were the issue.
I really don't know what to do or where to go from here, every source I've tried has given me a slight variation on what I have already attempted, and I'm no closer to getting this to work. Please help, thanks.
uj5u.com熱心網友回復:
您的 docker 應用程式正在5000容器內的埠上運行,但是在您的 dockerrun命令中,您將port8080 與8080容器內的埠系結,而應該是5000。由于容器內的埠上沒有運行任何8080內容,因此您收到403錯誤訊息
命令應該是
docker run --rm -it -p 8080:5000 myapp:latest
從主機您可以訪問埠 8080 上的應用程式,即:
127.0.0.1:8080/data # access from host machine
127.0.0.1:5000/data # 從容器內部訪問
我剛剛注意到,您沒有在互聯網/外部使用中公開應用程式,在 Dockerfile 的最后一行添加 arg "--host=0.0.0.0"
CMD ["python3", "-m" , "flask", "run", "--host=0.0.0.0"]
在 docker build 并發布埠后,您應該能夠訪問該應用程式。
uj5u.com熱心網友回復:
這最終奏效了,謝謝@Tasnuva
Dockerfile,附加 CMD 與--host
CMD [ "python3", "-m" , "flask", "run", "--host=0.0.0.0"]
在 CLI 中,
$ docker run --rm -it -p 8080:5000 myapp:latest
在 Postman 中訪問端點127.0.0.1:8080
uj5u.com熱心網友回復:
在 dockerfile 你需要公開你的埠
...
ENV FLASK_APP="app.py"
EXPOSE 5000
CMD ["python3", "-m" , "flask", "run"]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/439575.html
