1

On my laptop I can start simple flask app:

import os
import io
from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
        s = """
                This is a localhost!
        """
        return (s)

if __name__ == "__main__":
        app.run(host='0.0.0.0', port=3000, debug=True)

And when do curl localhost:3000 on my laptop - I can get a good response.

But when I start a docker image and put same code and start it with same version of Python - it shows as running but when I do from within a docker curl localhost:3000 - do not get any response (it just hangs and nothing happens).

How to enable localhost (routing) inside docker? Thanks.

Joe
  • 11,983
  • 31
  • 109
  • 183
  • did you try to ping localhost? where does it route? Also, read https://stackoverflow.com/questions/24319662/from-inside-of-a-docker-container-how-do-i-connect-to-the-localhost-of-the-mach – CIsForCookies Jul 08 '19 at 13:36
  • ```ping localhost PING localhost (127.0.0.1) 56(84) bytes of data. 64 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=64 time=0.081 ms``` – Joe Jul 08 '19 at 13:51
  • Can you describe how you're building and running the application? – David Maze Jul 08 '19 at 14:47
  • Did not do any binding or routing. What is the correct procedure? – Joe Jul 08 '19 at 15:01
  • The official Docker [Get Started, Part 2: Containers](https://docs.docker.com/get-started/part2/) tutorial walks through a Python example much like this. You're most likely missing a `docker run -p` option? Also remember that every container has its own notion of what `localhost` is and it's clearest to just avoid that hostname (and the equivalent 127.0.0.1 IPv4 address) in Docker-related questions. – David Maze Jul 09 '19 at 23:59

1 Answers1

-1

Change your code to

app.run(host='127.0.0.1', port=3000, debug=True)

and check if localhost is defined in /etc/hosts.

Exolon
  • 1
  • 1
  • Tried this and did not help. How `/etc/hosts` should be set? – Joe Jul 08 '19 at 14:01
  • 127.0.0.1 localhost – Exolon Jul 08 '19 at 14:05
  • This will actively prevent the application from working in Docker. It must be `host='0.0.0.0'` as shown in the question. (This is a pretty frequently-asked Docker question.) – David Maze Jul 08 '19 at 14:37
  • 1
    @DavidMaze so what is the solution? – Joe Jul 09 '19 at 20:51
  • 1
    @Joe Try to create a own docker network ```docker network create mynet``` and then start your container in this net and give him a hostname like this ```docker run -p 3000:3000 --net=mynet --ip=172.18.0.2 --hostname=myservice.foobar.com ```. Then you should be able to reach your service from host with ip (you could also set /etc/host on the host to know myservice.foobar.com) and within docker with myservice.foobar.com. (If you have troubles reaching the network on host, you need to add a static route : route /P add 172.18.0.0 MASK 255.255.0.0 10.0.75.2 – Exolon Jul 10 '19 at 05:57