我在 python 容器中公開埠有一個問題。在容器內部正確使用埠,但我無法將其暴露在外部,盡管影像使用埠引數運行。
docker run -d -p 8080:8080 api_python:0.1
main.py是:
from http.server import BaseHTTPRequestHandler, HTTPServer
hostName = "localhost"
serverPort = 8080
class MyServer(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes("<html><head><title>https://pythonbasics.org</title></head>", "utf-8"))
self.wfile.write(bytes("<p>Request: %s</p>" % self.path, "utf-8"))
self.wfile.write(bytes("<body>", "utf-8"))
self.wfile.write(bytes("<p>This is an example web server.</p>", "utf-8"))
self.wfile.write(bytes("</body></html>", "utf-8"))
if __name__ == "__main__":
webServer = HTTPServer((hostName, serverPort), MyServer)
print("Server started http://%s:%s" % (hostName, serverPort))
try:
webServer.serve_forever()
except KeyboardInterrupt:
pass
webServer.server_close()
print("Server stopped.")
影像建立: docker build -t api_python:0.1 .
Dockerfile是:
FROM python:3.8-slim-buster
RUN mkdir "api"
COPY api/MyServer.py api
WORKDIR api
ENTRYPOINT ["python","main.py"]
非常感謝您的回答。
uj5u.com熱心網友回復:
根據您的代碼,您似乎在 localhost:8080 上運行服務器。
hostName = "localhost"
serverPort = 8080
webServer = HTTPServer((hostName, serverPort), MyServer)
print("Server started http://%s:%s" % (hostName, serverPort))
容器確實有一個 localhost 介面,但它是容器本地的。您需要將埠 8080 系結到面向外部的網路,以便容器外部的任何內容都可以訪問它。
嘗試設定hostName不同的值:
hostName = "0.0.0.0"
0.0.0.0將系結到容器中所有面向外部的介面。這是一個方便的簡寫,因為您事先不知道容器的 IP,并且它會在沒有通知的情況下更改。
現在外部網路已經監聽了 8080 埠,外部的埠映射器將能夠訪問容器中 8080 埠后面的代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/487077.html
