首页 > 解决方案 > 无法使用 vscode 在 docker 中运行 python flask 应用程序(来自教程)

问题描述

我通过本教程构建了一个示例烧瓶应用程序
之后我尝试用它构建一个 docker 并按照本教程中的步骤进行操作

该应用程序在 localhost 中以调试模式运行。
docker 的构建没有任何错误。
当我尝试在调试模式下运行 docker 时,会弹出一个错误,我不知道为什么

 * Serving Flask app "hello_app\__init__.py"
 * 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
Usage: python -m flask run [OPTIONS]
Try 'python -m flask run --help' for help.

Error: Could not import "hello_app\__init__".

我尝试"hello_app\__init__:app"过以及"hello_app\__webapp__:app"dockerfile 中的入口点 - 总是同样的问题。

这是我的项目结构:

在此处输入图像描述

__初始化__.py:

from flask import Flask
app = Flask(__name__) # Flask instance named app

webapp.py:

# Entry point for the application.
from . import app    # For application discovery by the 'flask' command.
from . import views  # For import side-effects of setting up routes.

启动.json:

{"version": "0.2.0", "configurations": [{"name": "Python: Flask", "type": "python", "request": "launch", "module": "flask", "env": {"FLASK_APP": "hello_app/webapp", "FLASK_ENV": "development"}, "args": ["run", "--no-debugger"], "jinja": true}, {"name": "Docker: Python - Flask", "type": "docker", "request": "launch", "preLaunchTask": "docker-run: debug", "python": {"pathMappings": [{"localRoot": "${workspaceFolder}", "remoteRoot": "/app"}], "projectType": "flask"}}]}

Dockerfile:

# For more information, please refer to https://aka.ms/vscode-docker-python
FROM python:3.8-slim-buster

EXPOSE 5000

# Keeps Python from generating .pyc files in the container
ENV PYTHONDONTWRITEBYTECODE=1

# Turns off buffering for easier container logging
ENV PYTHONUNBUFFERED=1

# Install pip requirements
COPY requirements.txt .
RUN python -m pip install -r requirements.txt

WORKDIR /app
COPY . /app

# Creates a non-root user with an explicit UID and adds permission to access the /app folder
# For more info, please refer to https://aka.ms/vscode-docker-python-configure-containers
RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app
USER appuser

# During debugging, this entry point will be overridden. For more information, please refer to https://aka.ms/vscode-docker-python-debug
CMD ["gunicorn", "--bind", "0.0.0.0:5000", "hello_app\__init__:app"]

标签: python-3.xdockerflaskvisual-studio-code

解决方案


在 launch.json 中添加了条目(在“Docker:Python - Flask”下),它可以工作:

        "env": {
            "FLASK_APP": "hello_app/webapp.py",
            "FLASK_ENV": "development"
        },

在 dockerfile 中:"hello_app\__webapp__:app"


推荐阅读