title: Docker process opens TCP port, but connection is refused
body: <p>How can I run a simple server listening on a port, inside a Docker container?</p>
  
  <p>(In case it matters, this is a MacOS X 10.13.6 host.)</p>
  
  <p>When I run a simple HTTP Server:</p>
  
  <pre class="lang-sh prettyprint-override"><code>python3 -m http.server 8001
  </code></pre>
  
  <p>the process starts correctly, and it listens correctly on that port (confirmed with <code>telnet localhost 8001</code>).</p>
  
  <p>When I run a Docker container, it also runs the process correctly, but now the connection is refused.</p>
  
  <p>web-api/Dockerfile:</p>
  
  <pre><code>FROM python:3.7
  CMD python3 -m http.server 8001
  </code></pre>
  
  <p>docker-compose.yaml:</p>
  
  <pre><code>version: '3'
  services:
    web-api:
      hostname: web-api
      build:
        context: ./web-api/
        dockerfile: Dockerfile
      expose:
        - "8001"
      ports:
        - "8001:8001"
      networks:
        - api_network
  networks:
    api_network:
      driver: bridge
  </code></pre>
  
  <p>When i start the container(s), it is running the HTTP server:</p>
  
  <pre class="lang-none prettyprint-override"><code>$ docker-compose up --detach --build
  Building web-api
  […]
  
  $ docker ps
  CONTAINER ID        IMAGE                COMMAND                  CREATED             STATUS              PORTS                    NAMES
  1db4cd1daaa4        ipsum_web-api        "/bin/sh -c 'python3…"   8 minutes ago       Up 8 minutes        0.0.0.0:8001-&gt;8001/tcp   ipsum_web-api_1
  
  $ docker-machine ssh lorem
  
  docker@lorem:~$ ps -ef | grep http.server
  root     12883 12829  0 04:40 ?        00:00:00 python3 -m http.server 8001
  
  docker@lorem:~$ telnet localhost 8001
  [connects successfully]
  ^D
  
  docker@lorem:~$ exit
  
  $ telnet localhost 8001
  Trying ::1...
  telnet: connect to address ::1: Connection refused
  Trying 127.0.0.1...
  telnet: connect to address 127.0.0.1: Connection refused
  telnet: Unable to connect to remote host
  </code></pre>
  
  <p>What is configured incorrectly here, such that the server works <em>inside</em> the Docker container; but I get Connection refused on port 8001 when connecting from <em>outside</em> the container on its exposed port?</p>