Python + FastAPI + OracleCloud:如何将我在 Oracle Cloud 上的 python fastapi 端点公开到 Internet

Python + FastAPI + OracleCloud: How to expose my python fastapi endpoint on Oracle Cloud to Internet

我有一个 Python + FastAPI restful API 项目 运行 Oracle Cloud VM 实例的免费层。

我使用 Gunicorn 为 api 提供服务,还安装了 Nginx 以备不时之需。

我已经用

测试了我的 运行 项目

curl http://localhost:8000

我可以看到我的 API 回复。

现在我的问题是:如何在 Internet 外部公开此 api 端点?


更新 1

我用这个命令开始了我的 Python API 项目:

gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app --timeout 1200 -b 0.0.0.0

我看到了下面的消息:

[2021-05-23 00:40:28 +0000] [3850] [INFO] Starting gunicorn 20.0.2
[2021-05-23 00:40:28 +0000] [3850] [INFO] Listening at: http://0.0.0.0:8000 (3850)
[2021-05-23 00:40:28 +0000] [3850] [INFO] Using worker: uvicorn.workers.UvicornWorker
[2021-05-23 00:40:28 +0000] [3853] [INFO] Booting worker with pid: 3853
[2021-05-23 00:40:28 +0000] [3854] [INFO] Booting worker with pid: 3854
[2021-05-23 00:40:28 +0000] [3857] [INFO] Booting worker with pid: 3857
[2021-05-23 00:40:28 +0000] [3858] [INFO] Booting worker with pid: 3858
[2021-05-23 00:42:04 +0000] [3853] [INFO] Started server process [3853]
[2021-05-23 00:42:04 +0000] [3857] [INFO] Started server process [3857]
[2021-05-23 00:42:04 +0000] [3857] [INFO] Waiting for application startup.
[2021-05-23 00:42:04 +0000] [3858] [INFO] Started server process [3858]
[2021-05-23 00:42:04 +0000] [3858] [INFO] Waiting for application startup.
[2021-05-23 00:42:04 +0000] [3858] [INFO] Application startup complete.
[2021-05-23 00:42:04 +0000] [3853] [INFO] Waiting for application startup.
[2021-05-23 00:42:04 +0000] [3853] [INFO] Application startup complete.
[2021-05-23 00:42:04 +0000] [3857] [INFO] Application startup complete.
[2021-05-23 00:42:04 +0000] [3854] [INFO] Started server process [3854]
[2021-05-23 00:42:04 +0000] [3854] [INFO] Waiting for application startup.
[2021-05-23 00:42:04 +0000] [3854] [INFO] Application startup complete.

然后我从计算 >> 实例 >> 实例详细信息面板复制 IP 地址并从我的 Chrome 访问它。直截了当,它告诉我

Unable to connect

也阅读了几篇关于使用 Nginx 的文章,并尝试过,但没有成功。


更新 2

使用 curl 从我的本地计算机访问网站

$ curl http://168.138.12.192:8000/
curl: (7) Failed to connect to 168.138.12.192 port 8000: No route to host

然而,当直接使用curl访问IP时,我能够获得默认的Nginx网站。 $卷曲http://168.138.12.192

您是否更改了 /var/www/html 目录下的默认 html 页面?如果不尝试根据您的要求自定义 html 页面,看看它是否适合您,否则当使用 public IP 从浏览器访问时,它只会显示默认的 nginx 页面。

除此之外,还要检查安全列表和 OS 防火墙中是否允许端口 8000。 http 请求的默认端口为 80,您需要在配置文件中将默认端口从 80 更改为 8000 才能使其正常工作。参考此页面这可能有用 How to Change Apache HTTP Port in Linux.

终于,我发现了我漏掉的东西:

sudo iptables -I INPUT -p tcp -s 0.0.0.0/0 --dport 8000 -j ACCEPT 

我必须运行这个命令来打开端口 8000(是的,我的网站正在使用端口 8000)。

我以为我已经添加了Ingress Rule来接受tcp 8000,但结果我仍然需要运行上述命令

我不太明白为什么要这样做,但它解决了问题。