Search code examples
dockernginxwebsocketdocker-composetraefik

Accessing docker container websocket through nginx or traefik via html web page?


I have two docker containers running - one has a websocket and the other is an nginx container. Setup using docker-compose.yml as follows:

version: "3.5"

  websocket: 
    build:
      context: .
      dockerfile: Dockerfile
    ports: 
      - "6000:7000"

  nginx:
    image: nginx:alpine
    restart: always
    ports:
      - "120:80"

In my index.html in the nginx container, I currently have to set socketUrl: "http://192.168.X.X:6000",i.e. the local IP address for the websocket container.

Is there a way of setting up nginx so that socketUrl: "http://websocket:7000"? Either using nginx or traefik?

If I run on different machines I have to manually edit the socketUrl for the new machine. I'd like the setup to be standard across machines so that I can access the websocket via html at http://192.168.X.X:120


Solution

  • Use links to access the other container via hostname:

    version: "3.5"
    
    services:
      websocket: 
        build:
          context: .
          dockerfile: Dockerfile
        container_name: websocket
        ports: 
          - "6000:7000"
    
      nginx:
        image: dperson/nginx
        container_name: nginx
        ports:
          - "120:80"
        environment:
          - STREAM=0.0.0.0:80;websocket:7000
        links:
          - websocket
    

    if this doesn't work, force them to be on the same network:

    version: "3.5"
    
    services:
      websocket: 
        build:
          context: .
          dockerfile: Dockerfile
        container_name: websocket
        ports: 
          - "6000:7000"
        networks:
          - default
    
      nginx:
        image: dperson/nginx
        container_name: nginx
        ports:
          - "120:80"
        environment:
          - STREAM=0.0.0.0:80;websocket:7000
        links:
          - websocket
        networks:
          - default
    
    networks:
      default: