简体   繁体   English

在 Docker 中为 Python 容器公开端口

[英]Expose port in Docker for Python container

I have one problem with expose the port in python container.我在 python 容器中公开端口有一个问题。 Inside the container working the port correctly, but I cannot expose it outside, despite the image run with a parameter for the port.在容器内部正确使用端口,但我无法将其暴露在外部,尽管图像使用端口参数运行。

docker run -d -p 8080:8080 api_python:0.1

main.py is: 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.")

Image was built: docker build -t api_python:0.1 .图像已构建: docker build -t api_python:0.1 .

Dockerfile is: Dockerfile是:

FROM python:3.8-slim-buster
RUN mkdir "api"
COPY api/MyServer.py api
WORKDIR api
ENTRYPOINT ["python","main.py"]

Thank you very much for your answer.非常感谢您的回答。

Based on your code, you seem to be running the server on localhost:8080.根据您的代码,您似乎在 localhost:8080 上运行服务器。

hostName = "localhost"
serverPort = 8080
webServer = HTTPServer((hostName, serverPort), MyServer)
print("Server started http://%s:%s" % (hostName, serverPort))

A container does have a localhost interface, but it is local to the container .容器确实有一个 localhost 接口,但它是容器本地的 You need to bind port 8080 to the external-facing network in order for anything outside of your container to reach it.您需要将端口 8080 绑定到面向外部的网络,以便容器外部的任何内容都可以访问它。

Try setting the value for hostName differently:尝试以不同方式设置hostName的值:

hostName = "0.0.0.0"

0.0.0.0 will bind to all of the externally-facing interfaces in the container. 0.0.0.0将绑定到容器中所有面向外部的接口。 This is a convenient shorthand since you don't know the container's IP in advance, and it will change without notice.这是一个方便的简写,因为您事先不知道容器的 IP,并且它会在没有通知的情况下更改。

Now that the external network has port 8080 listening, the port mapper from outside will be able to reach the code behind port 8080 in your container.现在外部网络已经监听了 8080 端口,来自外部的端口映射器将能够访问容器中 8080 端口后面的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM