Leonardo
Leonardo

Reputation: 1363

Cannot access application from docker

I'm new to Docker and trying to put my python application into a image to share with a co-worker. I could build it and could run (below is the application output), but I can't access it from browser.

Here is the Dockerfile:

FROM larsklitzke/mysql-python3.5:latest

RUN mkdir /home/app
COPY . /home/app

RUN pip install boto3
RUN pip install -U flask
RUN pip install requests
RUN pip install Cython
RUN pip install numpy
RUN pip install pandas

WORKDIR /home/app/src

CMD ["python", "/home/app/src/app_web.py"]

I have built the image with the following command: docker build -t leonardo/python-app.

Then I ran the application using docker run -p 5000:5000 --name app leonardo/python-app which generate the following output:

* Serving Flask app "app_web" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
  Use a production WSGI server instead.
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 200-336-459

Nothing happens when I try to access the application with http://127.0.0.1:5000/.

When I ran docker network ls, there were 3 networks. One of them shows the container node pointing to my application, and it is a different IP address (172.17.0.2). But also does not work with this IP.

What is wrong with my setup?

Upvotes: 1

Views: 1675

Answers (2)

Itamar Turner-Trauring
Itamar Turner-Trauring

Reputation: 3890

127.0.0.1 means "the local machine".

Containers run in their own network namespace. So each container (by default) has its own 127.0.0.1, separate from the host 127.0.0.1.

Just like if you are listening on 127.0.0.1 on computer A and you connect to 127.0.0.1 computer B it won't work, similarly with containers.

The solution is to listen on the external IP of your container, which is where Docker forwards traffic when you do portforwarding with -p 5000:5000. In your case this is 172.17.0.2. However, that external IP can change on container restarts, so the easiest way to listen on the external IP is to listen on 0.0.0.0, which means "listen on all interfaces".

The way you do that is with an argument to Flask app's run() method: app.run(host='0.0.0.0').

Longer version, with handy diagrams: https://pythonspeed.com/articles/docker-connection-refused/

Upvotes: 2

Shashank V
Shashank V

Reputation: 11193

In your python app, you are binding to localhost interface at 127.0.0.1 which won't be accessible from outside the container. Change it to 0.0.0.0

Upvotes: 0

Related Questions