无法访问在 Docker 容器中运行的 Flask 服务器

时间:2021-04-15 09:32:05

标签: docker ubuntu flask

我正在构建一个可以在我的机器上正确运行的 Flask + React webapp。我尝试对它进行泊坞化。我可以构建镜像 (stiko:demo)、docker 运行、服务器启动:

enter image description here

但是当我尝试在浏览器上打开 https://0.0.0.0:5000/ 时,连接失败:

enter image description here

我已经搜索了一段时间,尝试从各种图像开始,尝试使用 ENDPOINT + CMD 命令,使用 flask run --host=0.0.0.0 但仍然是同样的问题。

  • 这是 Dockerfile:
FROM ubuntu:20.04

RUN useradd -ms /bin/bash ubuntu

RUN apt update
RUN apt install software-properties-common -y
RUN apt-get install libpq-dev -y
RUN add-apt-repository ppa:deadsnakes/ppa
RUN apt install python3.9 -y
RUN apt install python3-pip -y
RUN pip3 install --upgrade pip

WORKDIR /app/build
COPY ./build ./

WORKDIR /app/server
COPY ./server ./
RUN pip3 install -r requirements.txt --no-cache-dir
RUN pip3 install python-dotenv

ENV APP_SETTINGS="config.DevelopmentConfig"

EXPOSE 5000
  • app.py:
import sys
import os

from flask import Flask, request, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS, cross_origin

from models import User, Project, Image, db
from api import blueprints

app = Flask(__name__,
  static_folder='../build/static',
  template_folder="../build"
)

app.config.from_object(os.environ['APP_SETTINGS'])
db.init_app(app)
cors = CORS(app)

# Register the blueprints
for b in blueprints:
  app.register_blueprint(b)

@cross_origin
@app.route('/', defaults={'u_path': ''})
@app.route('/<path:u_path>')
def index(u_path=None):
  return render_template("index.html")

if __name__ == "__main__":
  app.run(host=('0.0.0.0'), port=5000, ssl_context='adhoc')

  • 项目结构:
  build
  |__static
  |__index.html
  |__ ...
  server
  |__app.py
  |__requirements.txt
  |__ ...
  Dockerfile

任何帮助将不胜感激,谢谢!

2 个答案:

答案 0 :(得分:0)

您的 Dockerfile 似乎没有启动您的烧瓶 API。尝试在最后添加一个 CMD。

FROM ubuntu:20.04

RUN useradd -ms /bin/bash ubuntu

RUN apt update
RUN apt install software-properties-common -y
RUN apt-get install libpq-dev -y
RUN add-apt-repository ppa:deadsnakes/ppa
RUN apt install python3.9 -y
RUN apt install python3-pip -y
RUN pip3 install --upgrade pip

WORKDIR /app/build
COPY ./build ./

WORKDIR /app/server
COPY ./server ./
RUN pip3 install -r requirements.txt --no-cache-dir
RUN pip3 install python-dotenv

ENV APP_SETTINGS="config.DevelopmentConfig"

EXPOSE 5000

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

答案 1 :(得分:0)

好吧,以防万一有人像我一样被卡住,网络技能可能为零:

Dockerfile 和 app.py 就好了。但是与其尝试在浏览器中访问 https://0.0.0.0:5000/,我应该尝试使用 https://127.0.0.1:5000/,它工作得非常好!