0

My virtualmachine's os is CentOS 7 and its docker version is 19.03.8. I create my own image python-image. I run the following codes to create a new container:

docker run -it -p 5555:5000 python-image /bin/bash

In the container, a python script named test.py is as follows:

# test.py
from flask import Flask

app = Flask(__name__)

@app.route('/')
def func():
    return "Hello docker!"


if __name__ == '__main__':
    app.run('0.0.0.0', port=5000)

Then I run python test.py and up the container.

In host shell, I run curl http://127.0.0.1:5555/ and it prints:

curl: (56) Recv failure: Connection reset by peer

I know that if specify --network as host when creating the container:

docker run -it --network host python-image /bin/bash

Starting the server and running curl http://127.0.0.1:5555/ in host will get the expected information. I wonder what should I do when keep default value of --network to get the same result.

S.Carven
  • 33
  • 7
  • This mostly looks right, except that your `docker run` commands are starting a bash shell instead of your server application. But the `-p` option, the `app.run()` call, and the port specifications all seem right. – David Maze Mar 24 '20 at 11:13
  • ...is the container running inside a VM, and the browser outside the VM on the host? You need to connect to the VM's IP address on the published port. – David Maze Mar 24 '20 at 11:15
  • @DavidMaze Browser is inside the VM. – S.Carven Mar 24 '20 at 12:47

1 Answers1

0

When not specified, the default network used by Docker is the Bridge network. To access the container, you should use its own IP address. It's possible to find the container's IP address with:

$ docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id

And then replace it by 127.0.0.1.

Or you could save it in a variable and try:

$ container_ip=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id)
$ curl http://${container_ip}:5555

foo0x29a
  • 806
  • 7
  • 6
  • This IP address doesn't work in a broad variety of common contexts (from MacOS or Windows hosts, if the browser isn't on the same physical host, if the container is running inside a VM). There's not usually a reason to look up the container-private IP address; you should generally use a `docker run -p` published port to connect to it, as shown in the question. – David Maze Mar 24 '20 at 11:16