我已经设置了一个 Python Flask
项目以指向在 interpreter
中运行的 Docker
:
从 Flask
启动 PyCharm IDE
应用会产生以下输出:
51be5e336622:python3 -u /opt/project/app.py
Starting server
* Serving Flask app "app" (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: on
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
* Restarting with stat
Starting server
* Debugger is active!
* Debugger PIN: 328-461-278
尝试打开 http://localhost:5000/ 导致页面未找到错误。
如果我使用 Docker 和 Dockerfile 运行应用程序:
FROM python:3.8-slim-buster
WORKDIR /app
COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt
COPY . .
EXPOSE 5000
#CMD [ "python3", "-m" , "flask", "run", "--host=0.0.0.0"]
CMD [ "python3", "-u" , "/app/app.py"]
以上 Dockerfile 构建了 PyCharm 连接到的容器,并在 Pycharm 中配置为:
使用命令 Docker
运行 docker run -p 5000:5000 services
容器,应用在 http://localhost:5000/ 上成功启动。
我是否需要将 PyCharm IDE 的 5000 端口映射到运行在 5000 端口上的 Docker 容器?如何实现这一点,PyCharm IDE 中似乎没有选项?
答案 0 :(得分:2)
在 https://blog.jetbrains.com/pycharm/2017/03/docker-compose-getting-flask-up-and-running/ 的帮助下,现在可以正常工作了。
Dockerfile:
FROM python:3.8-slim-buster
WORKDIR /app
COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt
COPY . .
EXPOSE 5000
CMD [ "python3", "-m" , "flask", "run", "--host=0.0.0.0"]
app.py 中的 main 方法:
if __name__ == '__main__':
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
logging.basicConfig(level=logging.INFO,
filename='./logs/' + str(
int(round(time.time() * 1000))) +'trade.log',
filemode="a+",
format="%(asctime)-15s %(levelname)-8s %(message)s",
datefmt='%Y-%m-%d %H:%M:%S')
logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
print('Starting server')
app.run(host="0.0.0.0", port=5000, debug=True)
docker-compose.yml,注意使用 5000 端口:
version: '2'
services:
web:
build: .
ports:
- "5000:5000"
volumes:
- .:/app
启动docker-compose:
docker-compose up
更新 PyCharm 以使用 docker compose 实例:
在 app.py 中执行 main 的输出:
Attaching to ml-services_web_1
web_1 | Starting server
web_1 | * Serving Flask app "app" (lazy loading)
web_1 | * Environment: production
web_1 | WARNING: This is a development server. Do not use it in a production deployment.
web_1 | Use a production WSGI server instead.
web_1 | * Debug mode: on
web_1 | * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
web_1 | * Restarting with stat
web_1 | Starting server
web_1 | * Debugger is active!
web_1 | * Debugger PIN: 828-722-345
web_1 | 172.20.0.1 - - [06/Apr/2021 13:36:32] "GET / HTTP/1.1" 200 -
http://localhost:5000/ 现在可以访问了。