monadoboi
monadoboi

Reputation: 1811

Docker container can't connect to server running on localhost

I have a python file running a server:

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import json

class S(BaseHTTPRequestHandler):
    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()

    def do_GET(self):
        self._set_headers()
        with open('files.json') as myfile:
            self.wfile.write(myfile.read())

....

def run(server_class=HTTPServer, handler_class=S, port=8080):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print 'Starting httpd...'
httpd.serve_forever()

And another doing a get request: import requests

SESSION = requests.Session()
SESSION.trust_env = False

url = "http://localhost:8080"
response = SESSION.get(url)
data = response.json()

This works fine when I run the two normally. However when I containerise the app (not the server), requests throws this error at me:

raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=8080): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f7ec03e5ed0>: Failed to establish a new connection: [Errno 111] Connection refused',))

I assume this is because docker somehow prevents me from connecting to my server on localhost:8080?

Thanks for you help ☺

Upvotes: 1

Views: 4340

Answers (1)

Grimmy
Grimmy

Reputation: 4137

A container is meant to be an isolated environment. It's a "jail" for running processes protecting the host os. Think of containers as a virtual machine with its own ip address. localhost would be the container trying to connect to itself.

I'm guessing you could contact port 8080 on the host using its public ip address.

It would make more sense to run the server in docker. Then you can map a port in the server container to a port on your host. Then your client would work as expected.

The two most common ways a container can interact with the host os is:

  • When mapping network ports from the container to to host
  • When mapping files as volumes from the host into the container

It's fairly restrictive for very good reasons.

Upvotes: 1

Related Questions