Docker connect NodeJS container with Apache container in front end JS

谁都会走 提交于 2020-01-06 05:27:10

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/48845838/docker-connect-nodejs-container-with-apache-container-in-front-end-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!