Home > Mobile >  Expose port in Docker for Python container
Expose port in Docker for Python container

Time:06-06

I have one problem with expose the port in python container. 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:

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 .

Dockerfile is:

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.

CodePudding user response:

Based on your code, you seem to be running the server on 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. You need to bind port 8080 to the external-facing network in order for anything outside of your container to reach it.

Try setting the value for hostName differently:

hostName = "0.0.0.0"

0.0.0.0 will bind to all of the externally-facing interfaces in the container. This is a convenient shorthand since you don't know the container's IP in advance, and it will change without notice.

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.

  • Related