MS Azure - python http.server - 连接被拒绝

MS Azure - python http.server - Connection refused

我有一个非常简单的 Ubuntu VM 托管在 MS Azure 上。我有这个简单的 python 程序 运行:

import http.server
from prometheus_client import start_http_server
from prometheus_client import Counter

REQUESTS  = Counter('hello_worlds_total','Hello World requested')

class MyHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        REQUESTS.inc()
        self.send_response(200)
        self.end_headers()
        self.wfile.write("Hello world")

if __name__ == "__main__":
    start_http_server(8001)
    server = http.server.HTTPServer(('localhost',8000), MyHandler)
    server.serve_forever()
}}}

当我从我的电脑上点击 url http://VM_AZURE_IP:8001 时,它会回复 Promethues 输出。当我尝试 http://VM_AZURE_IP:8000 时,连接被拒绝。 newtork 规则没问题,如果我将 start_http_server(8001) 切换到 start_http_server(8000) 并将 http.server.HTTPServer(('localhost',8000), MyHandler) 切换到 http.server.HTTPServer(('localhost',8001), MyHandler),我会得到 promethues 指标命中 http://VM_AZURE_IP:8000 和端口 8001 上的连接被拒绝

您可以像这样更改您的代码,并确保您已在与 Ubuntu VM 关联的 NSG 的入站规则中添加端口 8001,8000。

import http.server
from prometheus_client import start_http_server
from prometheus_client import Counter

REQUESTS  = Counter('hello_worlds_total','Hello World requested')

class MyHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        REQUESTS.inc()
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b"Hello world")   # add b

if __name__ == "__main__":
    start_http_server(8000)
    server = http.server.HTTPServer(('0.0.0.0',8001), MyHandler)  # chang to IP address 0.0.0.0
    print("server on!")
    server.serve_forever()

它对我有效。