Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

making requests to localhost from inside docker container

I have an application runing on my localhost at port 8080. I have some python code that consumes that service. The code runs fine on my base system but as soon as I put it inside a docker container I get urllib2.URLError: <urlopen error [Errno 111] Connection refused>. I have another application that exposes an api at port 6543. Same problem.

I assume I need to tell docker that it's allowed to consume certain localhost ports. How do I do that?

Here are some more specific details:

I can execute this line of code just fine on my base system:

urllib2.urlopen(req, json.dumps(dData))

but when I try to do it from inside a docker container then I get:

File "/usr/lib/python2.7/urllib2.py", line 154, in urlopen
  return opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 431, in open
  response = self._open(req, data)
File "/usr/lib/python2.7/urllib2.py", line 449, in _open
  '_open', req)
File "/usr/lib/python2.7/urllib2.py", line 409, in _call_chain
  result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 1227, in http_open
  return self.do_open(httplib.HTTPConnection, req)
File "/usr/lib/python2.7/urllib2.py", line 1197, in do_open
  raise URLError(err)

urllib2.URLError: <urlopen error [Errno 111] Connection refused>

I've tried adding permissions to docker.sock

ls -l /var/run/docker.sock      
=> srw-rw-rwx 1 root docker 0 Feb 17 11:09 /var/run/docker.sock
like image 220
Sheena Avatar asked Feb 24 '17 06:02

Sheena


People also ask

Can I access localhost from Docker?

Accessing the Host With the Default Bridge ModeYou just need to reference it by its Docker network IP, instead of localhost or 127.0. 0.1 . Your host's Docker IP will be shown on the inet line. Connect to this IP address from within your containers to successfully access the services running on your host.

How do I connect to a Docker container locally?

To connect to a container using plain docker commands, you can use docker exec and docker attach . docker exec is a lot more popular because you can run a new command that allows you to spawn a new shell. You can check processes, files and operate like in your local environment.

How do I map a Docker container port to a local port?

Map TCP port 80 in the container to port 8080 on the Docker host for connections to host IP 192.168.1.100. Map UDP port 80 in the container to port 8080 on the Docker host. Map TCP port 80 in the container to TCP port 8080 on the Docker host, and map UDP port 80 in the container to UDP port 8080 on the Docker host.


1 Answers

Create your python container with argument -net host,it will share address and port with host,so it can access progress which is running on host.

Refer to my another answer: https://stackoverflow.com/a/48069763/5465023

like image 65
亚里士朱德 Avatar answered Oct 20 '22 15:10

亚里士朱德