简体   繁体   English

Docker将NodeJS容器与前端JS中的Apache容器连接

[英]Docker connect NodeJS container with Apache container in front end JS

I am building a chat application that i am implementing in Docker. 我正在构建我在Docker中实现的聊天应用程序。 I have a NodeJS container with socket.io and a container with apache server and website on it. 我有一个带有socket.io的NodeJS容器和一个带有apache服务器和网站的容器。

The thing is i need to connect to the website(with javascript) to the NodeJS server. 事情是我需要连接到网站(使用javascript)到NodeJS服务器。 I have looked at the Docker-compose docks and read about networking. 我查看了Docker组成的码头,并了解了网络。 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. 整个项目在容器外工作。我唯一不知道的是NodeJs容器和Apache容器之间的连接。

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? 谁能解释我如何将apache容器成功连接到NodeJS容器,以便它可以为socket.io.js文件提供服务?
I can give more of the source code if needed. 如果需要,我可以提供更多的源代码。

The nodejs service is exposing port 3001 not 3000. 3001:3000 is a port mapping which forwards :3001 to the :3000 container port. nodejs服务公开的端口不是3001,而不是nodejs 3001:3000是端口映射,它将:3001转发到:3000容器端口。 So you would need to point it to nodejs:3001 . 因此,您需要将其指向nodejs:3001

However, I don't think that'll work since the nodejs hostname is not accessible by the browser. 但是,我认为这不会起作用,因为浏览器无法访问nodejs主机名。 You need to point it to the host in which docker is running since you are exposing those ports there. 您需要将其指向运行docker的主机,因为您要在其中公开这些端口。 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. 换句话说,您不是从apache服务连接到nodejs服务器,而是通过浏览器从外部访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM