0

How can I run a simple server listening on a port, inside a Docker container?

(In case it matters, this is a MacOS X 10.13.6 host.)

When I run a simple HTTP Server:

python3 -m http.server 8001

the process starts correctly, and it listens correctly on that port (confirmed with telnet localhost 8001).

When I run a Docker container, it also runs the process correctly, but now the connection is refused.

web-api/Dockerfile:

FROM python:3.7
CMD python3 -m http.server 8001

docker-compose.yaml:

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

When i start the container(s), it is running the HTTP server:

$ 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->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

What is configured incorrectly here, such that the server works inside the Docker container; but I get Connection refused on port 8001 when connecting from outside the container on its exposed port?

  • @WilfredSmith The question is on-topic on both sites. Don't think you should get downvotes when posting an answer below. – nohillside May 21 at 9:13

You must log in to answer this question.

Browse other questions tagged .