【问题标题】:Flask doesn't render html page from docker [duplicate]Flask 不会从 docker 渲染 html 页面 [重复]
【发布时间】:2021-11-23 05:00:17
【问题描述】:

我有一个简单的烧瓶应用程序,它可以在没有 docker 的情况下工作,但在包装在 docker 容器中时没有回复。我怀疑我有一些地址搞砸了

from flask import Flask, render_template, request
import pandas as pd

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def uploadfile():
    if request.method == 'POST':  # check if the method is post
        df = pd.read_json(request.files.get('file'))
        return render_template('upload.html',  tables=[df.head().to_html(classes='data', header="true")])
    return render_template('upload.html')


if __name__ == '__main__':
    app.run(debug=True, port=5000)  # running the flask app

upload.html

<!doctype html>
<html>
  <head>
    <title>File Upload</title>
  </head>
  <body>
    <h1>File Upload</h1>
    <form 
      method="POST" 
      action="/" 
      enctype="multipart/form-data"
    >
      <p><input type="file" name="file"></p>
      <p><input type="submit" value="Submit"></p>
    </form>
    {% for table in tables %}
            {{ table|safe }}
    {% endfor %}
  </body>
</html>

项目树:

├── script.py
├── templates
    └── upload.html

Dockerfile:

FROM python:3.7-slim-buster

WORKDIR /app

COPY requirements.txt ./


RUN apt-get update 
RUN pip install --no-cache-dir -r requirements.txt


RUN mkdir /templates

COPY script.py /app/
COPY ./templates/ /app/templates/

RUN dir

CMD [ "python", "script.py" ]

我启动 docker 映像为

docker run -it --rm -p 5000:5000 online-app

日志如下:

* Serving Flask app "script" (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://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 416-968-407

我转到http://127.0.0.1:5000/,页面将永远加载。 我错过了什么?

UPD: 使用 app.run(debug=True, host=0.0.0.0, port=5000) # running the flask app 有类似的日志:

 * Running on http://172.17.0.2:5000/ (Press CTRL+C to quit)

但是链接也失效了

【问题讨论】:

    标签: python docker flask


    【解决方案1】:

    将监听主机IP改为0.0.0.0

    app.run(debug=True, host='0.0.0.0', port=5000)  # running the flask app
    

    当您尝试连接到http://127.0.0.1:5000 - 您尝试连接到物理服务器(docker 主机)的localhost 接口 但是烧瓶应用程序只监听容器内的localhost,容器外无法访问的内容

    【讨论】:

    • 我如你所说更改了host,当我打开链接时仍然永远加载`*在172.17.0.2:5000上运行(按CTRL+C退出)`在浏览器中
    • @JamesFlash 您必须在浏览器中使用http://127.0.0.1:5000 才能连接到 docker 容器外
    • 谢谢,问题出在 html 上,这里已解决 stackoverflow.com/questions/69408492/…
    【解决方案2】:

    我不是 Flask 方面的专家,但根据您的日志,它似乎没有在正确的地址上监听。实际上,在容器内部,127.0.0.1 不会与来自容器外部的请求匹配(例如,它可以与来自容器内部的 Curl 一起使用)。为了让它监听“非本地”(如“不是源自容器本身”)请求,它必须监听0.0.0.0

    【讨论】:

    • 我还有这个问题,你可以看下面的评论
    猜你喜欢
    • 2019-04-01
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多