Niverhawk
Niverhawk

Reputation: 270

Docker connect NodeJS container with Apache container in front end JS

I am building a chat application that i am implementing in Docker. I have a NodeJS container with socket.io and a container with apache server and website on it.

The thing is i need to connect to the website(with javascript) to the NodeJS server. I have looked at the Docker-compose docks and read about networking. The docs said that the address should be the name of the container. But when i try that i get the following error in my browser console:

GET http://nodejs:3000/socket.io/socket.io.js net::ERR_NAME_NOT_RESOLVED

The whole project works outside containers.The only thing that i cannot figure out is the connection between the NodeJs container and the Apache container.

code that throws the error:

<script type="text/javascript" src="//nodejs:3000/socket.io/socket.io.js"></script>

My docker compose file:

version: '3.5'

services:

  apache:
    build:
      context: ./
      dockerfile: ./Dockerfile
    networks:
      default:
    ports:
      - 8080:80
    volumes:
      - ./:/var/www/html
    container_name: apache

  nodejs:
    image: node:latest
    working_dir: /home/node/app
    networks:
      default:
    ports:
      - '3001:3000'
    volumes:
      - './node_server/:/home/node/app'
    command: [npm, start]
    depends_on:
      - mongodb
    container_name: nodejs

networks:
  default:
    driver: bridge

Can anyone explain me how to succesfully connect the apache container to the NodeJS container so it can serve the socket.io.js file?
I can give more of the source code if needed.

Upvotes: 0

Views: 3351

Answers (1)

Maroshii
Maroshii

Reputation: 4017

The nodejs service is exposing port 3001 not 3000. 3001:3000 is a port mapping which forwards :3001 to the :3000 container port. So you would need to point it to nodejs:3001.

However, I don't think that'll work since the nodejs hostname is not accessible by the browser. You need to point it to the host in which docker is running since you are exposing those ports there. If you are running this locally it might look like:

<script type="text/javascript" src="//localhost:3001/socket.io/socket.io.js"></script>

In other words, you are not connecting to the nodejs server from the apache service, you are accessing it externally through the browser.

Upvotes: 1

Related Questions