socket.io在docker-compose堆栈上(节点+ angular)

发布于 2025-01-23 23:15:18 字数 2800 浏览 2 评论 0原文

我正在尝试将socket.io集成到带有前端的Docker-Compose堆栈中(Angular + nginx)和后端(node.js express)。此实例的目的是在实例之间的实时消息中广播。 但是,当我使用nginx部署它时,这无效,而且我没有收到任何错误消息。我收到的唯一日志是从前端,它是“ localhost”上的代码 200 。

src-frontend-1 | 172.27.0.1--- [26/APR/2022:08:18:05 +0000] http:// localhost/“” Mozilla/5.0(Windows NT 10.0; Win64; X64)Applewebkit/537.36(Khtml,像Gecko一样)Chrome/100.0.0.4896.127 Safari/537.36 safari/

537.36我使用ng服务npm运行dev
在开发计算机上运行 在这里,我的后端:

const PORT = process.env.PORT || 8080;
const app = express();
const httpServer = new createServer(app);
const io = new Server(httpServer, {
  cors: {
    origin: {
      origin: "http://localhost:8080",
    },
    allowedHeaders: ["socket.io"],
    credentials: true,
  },
});

io.on("connection", (socket) => {
  console.log("new socket connected");
  socket.on("process", (data) => {
    console.log(`New data received : ${data}`);
    newDataSocket = data.isOperation; //Status of instances
    console.log("result data socket :", newDataSocket);

    socket.broadcast.emit("processChanged", data);
  }); // listen to the event
  socket.on("error", function (err) {
    console.log("Socket.IO Error");
    console.log(err); // this is changed from your code in last comment
  });
});

httpServer.listen(6379, () => {
  console.log(`[app with socket.io] : Listening on PORT 6379`);
});

配置前端core.module.ts for for for配置

import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
const config: SocketIoConfig = { url: /socket.io/, options: {} };

前端服务插座

export class SocketIoService {
  constructor(private socket: Socket) {}

  sendMessage(msg: object) {
    console.log('msg sended from front===>', msg);
    this.socket.emit('process', msg);
  }
  getMessage() {
    return this.socket.fromEvent<any>('processChanged')
  }
}

dockerfile backend

FROM node:14-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
# Bundle app source
COPY . .
EXPOSE 8080 6379
CMD [ "node", "app.js" ]

nginx配置

    location /socket.io/ {
        proxy_pass http://api:6379;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_http_version 1.1;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

和docker-compose文件

version: '3.4'

services:
  api:
    build:
      context: './backend'
    ports:
      - 8080:8080

  frontend:
    build:
      context: './frontend'
    ports:
      - 80:80
    depends_on:
      - api
    links:
      - api

I'm trying to integrate Socket.io into a docker-compose stack with a frontend (Angular + Nginx) and a backend (Node.JS Express). The goal of this instance is to broadcast in real-time messages between instances.
But that doesn't works when I'm deploying it using Nginx, and I don't received any errors messages. The only log I received is from the Frontend and it's a code 200 on "localhost".

src-frontend-1 | 172.27.0.1 - - [26/Apr/2022:08:18:05 +0000] "POST /socket.io/?EIO=4&transport=polling&t=O1aylEl&sid=KfZQUO36iFaqoKlWAAAA HTTP/1.1" 200 2 "http://localhost/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36" "-"

Note that code works when I run on my dev computer using ng serve and npm run dev
Here my backend:

const PORT = process.env.PORT || 8080;
const app = express();
const httpServer = new createServer(app);
const io = new Server(httpServer, {
  cors: {
    origin: {
      origin: "http://localhost:8080",
    },
    allowedHeaders: ["socket.io"],
    credentials: true,
  },
});

io.on("connection", (socket) => {
  console.log("new socket connected");
  socket.on("process", (data) => {
    console.log(`New data received : ${data}`);
    newDataSocket = data.isOperation; //Status of instances
    console.log("result data socket :", newDataSocket);

    socket.broadcast.emit("processChanged", data);
  }); // listen to the event
  socket.on("error", function (err) {
    console.log("Socket.IO Error");
    console.log(err); // this is changed from your code in last comment
  });
});

httpServer.listen(6379, () => {
  console.log(`[app with socket.io] : Listening on PORT 6379`);
});

Frontend core.module.ts for the configuration

import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
const config: SocketIoConfig = { url: /socket.io/, options: {} };

Frontend service Socket

export class SocketIoService {
  constructor(private socket: Socket) {}

  sendMessage(msg: object) {
    console.log('msg sended from front===>', msg);
    this.socket.emit('process', msg);
  }
  getMessage() {
    return this.socket.fromEvent<any>('processChanged')
  }
}

Dockerfile backend

FROM node:14-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
# Bundle app source
COPY . .
EXPOSE 8080 6379
CMD [ "node", "app.js" ]

Nginx configuration

    location /socket.io/ {
        proxy_pass http://api:6379;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_http_version 1.1;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

And the docker-compose file

version: '3.4'

services:
  api:
    build:
      context: './backend'
    ports:
      - 8080:8080

  frontend:
    build:
      context: './frontend'
    ports:
      - 80:80
    depends_on:
      - api
    links:
      - api

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风蛊 2025-01-30 23:15:18

更新

,有些人从我这边误解了,有些人错过了文档。

  1. NGX-Socket-io图书馆如果没有HTTP前面的前面,则不支持URL字符串。因此,我需要添加域。我使用/api没有http我的休息呼叫,并且以前可以使用,但
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
const config: SocketIoConfig = { url: 'http://localhost/socket.io', options: {} };
  1. 如果没有path,则在选项中没有使用此库,ngx -socket-io添加/socket.io默认情况下。
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
const config: SocketIoConfig = { url: 'http://localhost', options: {} };
  1. 我还将在后端选项中添加PATH,不确定它非常有用
const io = new Server(httpServer, {
  path: "/socket.io",
  cors: {
    origin: [CORS_POLICY],
    methods: ["GET", "POST"]
  }
});

并且有效。
我的要求是200,但是在Chrome的网络控制台中,我错过了“错误的名称空间”错误,这有助于我找到原因。

UPDATE

So, some misunderstood from my side and some miss in the documentation.

  1. The ngx-socket-io library doesn't support url string if there not http front of it. So I need to add the domain. I used /api without http for my REST calls and it works before but not with this library
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
const config: SocketIoConfig = { url: 'http://localhost/socket.io', options: {} };
  1. If no path in options, ngx-socket-io add /socket.io by default.
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
const config: SocketIoConfig = { url: 'http://localhost', options: {} };
  1. I also add path in the backend options, not sure it was very useful
const io = new Server(httpServer, {
  path: "/socket.io",
  cors: {
    origin: [CORS_POLICY],
    methods: ["GET", "POST"]
  }
});

And it's works.
My requests were 200 but in the network console of Chrome I missed the "wrong namespace" error, that help me to find the cause.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文