Search code examples
pythonpython-2.7dockerdockerfilesimplehttpserver

docker python simplehhtpserver not working


my python codes

# _*_ coding:utf-8 _*_

from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
import SocketServer

class testHTTPSERVER_RequestHandler(BaseHTTPRequestHandler):

    def do_GET(self):

        self.send_response(200)
        self.send_header('Content-type','text/html')
        self.end_headers()

        self.wfile.write("<html><body><h1>Hello world</h1></body></html>")

def run(server_class=HTTPServer,handler_class=BaseHTTPRequestHandler):
    print('starting server ....')
    server_address = ('127.0.0.1',8081)
    httpd = server_class(server_address,testHTTPSERVER_RequestHandler)
    print('running server')
    httpd.serve_forever()

run()

and docker file

FROM python:2.7-onbuild
#python:2.7.13-alpine dene
ADD testhttp_server.py /src/app/testhttp_server.py
WORKDIR /src/app/
EXPOSE 8081

CMD ["python","testhttp_server.py"]

docker run and logs

mozilla

so where is my mistake??I'm working on that during two days but I didn't find anything else


Solution

  • Change this

    server_address = ('127.0.0.1',8081)
    

    to

    server_address = ('0.0.0.0',8081)
    

    Listening to 127.0.0.1 inside docker container means you want to listen to traffic generated from inside the container only but when you map a host to container. It is sending the traffic from host to the IP of the container. Which id dynamic and not know before hand. So you need to listen to all interfaces inside the container. And that is why you should use 0.0.0.0