Docker Community Forums

Share and learn in the Docker community.

Can expose all ports, but not just one


#1

I’m trying to get a web server running inside a Docker container. Using Ubuntu 16.04. For the app, I’m just running a Hello World in Flask, per here, named app.py:

#!/usr/bin/env python
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
    return "Hello, World!"
if __name__ == '__main__':
    app.run(debug=True)

Dockerfile is:

FROM centos
RUN yum install -y epel-release
RUN yum -y update
RUN yum install -y python python-pip
RUN pip install flask
RUN mkdir -p /sandbox
ADD . /sandbox
WORKDIR /sandbox

If I run with --net host, it works as expected. I can navigate to localhost:5000 in my browser and see “Hello, World!”.

$ docker run --rm -d --net host flask-image ./app.py

But that exposes all my ports! I’d rather just expose the one I need. If I swap in -p 5000:5000, I see nothing. Chrome says " This site can’t be reached. The connection was reset."

$ docker run --rm -d --p 5000:5000 flask-image ./app.py

Sure looks to me like the port is being published:

$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                    NAMES
022fd4a1e40c        flask-image         "./app.py"          4 minutes ago       Up 4 minutes        0.0.0.0:5000->5000/tcp   focused_jennings

I have tried switching to a different port, pointing to the container IP address (per docker inspect), adding EXPOSE to the Dockerfile, adding -P to the command line, but no dice. I can’t seem to access that port without --net host.

Is this a bug? Am I doing something wrong? Please help!


#2

Of course, after hours of slamming my head against this, I figure it out as soon as I post the question…

Apparently, with --net host, the server can run on localhost (within the container). But to expose individual ports, the server needs to run on 0.0.0.0. So in app.py, it needs to be app.run(host="0.0.0.0", debug=True).

Per here