0

I am unable to access the app outside the container, when I exec inside the container and do curl localhost:8000 it is showing but the same app is not reflecting in the host browser. Any help would be appreciated. main.py

#!/usr/bin/env python

from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse
import json

class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        parsed_path = urlparse(self.path)
        self.send_response(200)
        self.end_headers()
        self.wfile.write(json.dumps({
            'myfavourite author name': 'shakespear',
        }).encode())
        returnx

if __name__ == '__main__':
    server = HTTPServer(('localhost', 8000), RequestHandler)
    print('Starting server at http://localhost:8000')
    server.serve_forever()

Dockerfile

FROM python:latest
COPY . ./
RUN pip install -r requirements.txt
EXPOSE 8000
CMD python main.py

requirements.txt

urllib3
httpserver

  • Docker creates a network per container, see https://docs.docker.com/network/. You should listen at 0.0.0.0 and expose the port 8000 (https://docs.docker.com/config/containers/container-networking/) – Mika Vatanen Apr 15 '22 at 09:23

1 Answers1

1

You need to bind to 0.0.0.0 for your program to accept connections from outside the container. Like this

if __name__ == '__main__':
    server = HTTPServer(('0.0.0.0', 8000), RequestHandler)
    print('Starting server at http://0.0.0.0:8000')
    server.serve_forever()
Hans Kilian
  • 18,948
  • 1
  • 26
  • 35