首页 > 解决方案 > 无法使用 docker 容器加载 python flask API

问题描述

我正在尝试使用 API 学习 Docker 容器。我用烧瓶创建了一个简单的 Hello World python REST API:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == '__main__':
    app.run(host="127.0.0.1", debug=True, port=8080)

这在我运行脚本并转到http://localhost:8080/时有效

这是我的 Dockerfile:

# Use an official Python runtime as a parent image
FROM python:2.7-slim

# Set the working directory to /app
WORKDIR /hello_world

# Copy the current directory contents into the container at /app
ADD . /hello_world

# Install any needed packages specified in requirements.txt
RUN pip install --trusted-host pypi.python.org -r requirements.txt

EXPOSE 8080

# Define environment variable
ENV NAME World

# Run app.py when the container launches
CMD ["python", "hello_world.py"]

要求.txt:

Flask

我的当前目录包含 Dockerfile、hello_world.py 和 requirements.txt。

docker build -t hello_world ." 我可以通过Running it with成功构建映像,并docker run -p 8080:8080 -t hello_world提供以下输出:

 Serving Flask app "hello_world" (lazy loading)
 * Environment: production
 WARNING: Do not use the development server in a production environment.
 Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 985-433-141

当我尝试访问http://127.0.0.1:8080/时,我收到“无法访问此页面”错误。你知道我做错了什么吗?谢谢你。

标签: pythonapidockerflask

解决方案


推荐阅读