I have a simple TypeScript program running on Docker, and this program would like to open a Websocket connection to an outside Websocket server. Something like this
----------------------- ------------------------------
| My Local Docker | | my.ws-server.somewhere.com |
| | | |
| WS client |---> Internet----->| WS server |
----------------------- ------------------------------
When I run (ts-node test.js) the code with the WS client on my dev environment outside Docker, it works fine and can connect without any issues:
let ws = new WebSocket("ws://my.ws-server.somewhere.com", [], { })
ws.onopen = () => {
console.log('Connection opened ok! ')
}
However, when I put this some thing inside Docker and run it there, the connection is refused. The program starts the connection attempt as it should, but there is just a timeout and the connection is never opened. I guess this has something to do with Docker network? If I want to open an outbound connection from Docker to the outside world, do I need to define some routes or something?
My Docker setup
Dockerfile
FROM node:12.18.3
RUN mkdir /src
WORKDIR /src
ADD ./package.json /src/package.json
RUN npm install
EXPOSE 3000
docker-compose.yml
version: "3.4"
services:
my-service:
container_name: my-service
restart: always
build:
context: .
dockerfile: my-service.dockerfile
volumes:
- ".:/src"
(I noticed that I can make this work by adding network_mode: "host" to docker compose, but that's not what I would really want to do so that I could keep the normal inbound port mappings)