dopatraman
dopatraman

Reputation: 13908

Cannot hit docker container running locally

Here's my Dockerfile:

FROM alpine:3.5


RUN apk add --no-cache python3 && \ 
    python3 -m ensurepip && \ 
    rm -r /usr/lib/python*/ensurepip && \ 
    pip3 install --upgrade pip setuptools && \ 
    rm -r /root/.cache 

# Copy files
COPY ./requirements.txt /app/requirements.txt
COPY ./main.py /app/main.py

# Install deps
RUN pip install --upgrade pip
RUN pip install --requirement /app/requirements.txt

# Set the default directory where CMD will execute
WORKDIR /app

EXPOSE 5000

CMD [ "python3", "-u", "./main.py" ]

and my main.py file: from flask im

port Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

After building the tag and running it via docker run <tag>, get logs saying the flask server was successfully started:

$ docker run test:latest
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

But I cannot hit the server in my browser.

I thought the problem may be in the port mapping, so I ran the container like this:

$ docker run -p 5000:5000 test:latest
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Still no dice. I am able to run the server outside of the container, simply by running python3 main.py. what am I doing wrong?

Upvotes: 3

Views: 2560

Answers (3)

Nicholas Porter
Nicholas Porter

Reputation: 2951

127.0.0.1 is the loopback address (also known as localhost).

0.0.0.0 is a non-routable meta-address used to designate an invalid, unknown, or non-applicable target (a ‘no particular address’ place holder). For things like address binding of network connections, the result can be to assign an appropriate interface address to the connection.

In Docker, the loopback address (127.0.0.1) of a container is not the same as the host. Use 0.0.0.0 as the host instead.

app.run(host='0.0.0.0')

Upvotes: 0

Robert
Robert

Reputation: 36823

The 127.0.0.1 address that you see is the localhost of the container networking, that is not the same as the main host. When exposing ports, docker maps a port binding in container internal IP (172.17....) to a port in the hosts interfaces.

So you must tell your flask to listen to all of its interfaces:

app.run(host='0.0.0.0')

Upvotes: 2

Ricardo Branco
Ricardo Branco

Reputation: 6079

The script is listening to 127.0.0.1 in the container, making it inaccessible from the host. It must listen to 0.0.0.0.

Upvotes: 4

Related Questions