Home > Enterprise >  Python WebSocket connection refused in Docker
Python WebSocket connection refused in Docker

Time:07-16

I have a python socketio application that works just fine when run locally. However, when I move it into Docker, external clients are unable to connect and throw this error:

socketio.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))

The WebSocket server is really basic and publishes to 0.0.0.0:8080. My client apps listen to localhost:8080. In my Docker container, I've exposed port 8080. I'm guessing that I'm setting up my container incorrectly.:

Dockerfile:

FROM python:latest

WORKDIR /path/to/project

COPY requirements.txt .

RUN pip install --no-cache-dir -r requirements.txt

docker-compose.yml

version: "3.9"

services:
  app:
    build: .
    working_dir: /path/to/project
    stdin_open: true
    tty: true
    ports:
      - "8080:8080"
    volumes:
      - type: bind
        source: .
        target: /path/to/project

I start up my container with docker-compose up and I'm using Docker Desktop (if that helps). I use this environment for development so I start my server with python my_server.py. The server starts successfully. What else am I missing?

I've tried the following based on what others have said about this problem online

  • Explicitly setting 0.0.0.0 to be the host
  • Using EXPOSE 8080 in my Dockerfile
  • Set the network mode to host

CodePudding user response:

Your container connectivity appears to be fine.

You have not specified any command to run in your container. In order to ensure your server is actually running on port 8080, you can add a CMD instruction in your Dockerfile or specify cmd in your docker-compose.yaml. This can be done with:

CMD ["python", "my_server.py"]

Or with docker-compose.yaml file as:

version: "3.9"

services:
  app:
    build: .
    working_dir: /path/to/project
    stdin_open: true
    tty: true
    command: python my_server.py #<== this overrides the Dockerfile CMD instruction
    ports:
      - "8080:8080"
    volumes:
      - type: bind
        source: .
        target: /path/to/project

You can learn more about command in docker-compose.yaml here.

That's also the recommended way to develop with docker. Running commands inside running containers for dev work is not the right way. You essentially run docker compose every time you test a new change. That avoids a lot of problems like these where connectivity doesn't work.

  • Related