我正在尝试在NodeJS docker容器中连接我的SocketIO服务器,但是我在客户端上收到此消息:
GET http://localhost:4500/socket.io/?EIO=3&transport=polling&t=MPdyL6j net::ERR_CONNECTION_REFUSED
我的服务器Dockerfile如下所示:
FROM node:alpine
WORKDIR /
RUN apk update && apk upgrade && \
apk add --no-cache bash git openssh
RUN npm install -g nodemon
# Copy package.json
COPY package.json /package.json
# Install packages
RUN npm install
EXPOSE 4500
CMD nodemon ./server/index.js
在我的docker-compose文件中,我有:
services:
socketio:
build: ./packages/public/socketio
hostname: socketio
restart: always
container_name: socketio
volumes:
- ./packages/public/socketio:/server
- ./packages/config:/config
environment:
- PORT=4500
- NODE_ENV=production
- REDIS_HOST=redis
ports:
- "4500:4500"
depends_on:
- redis
最后,这就是我初始化服务器的方法(在一个类中):
const express = require('express');
const app = express();
const server = app.listen(PORT);
this.ioServer = require('socket.io').listen(server);
...
我认为我做得正确,如果我从可以使用的容器外部执行同一服务器:
import io from 'socket.io-client';
const socket = io.connect('http://localhost:4500/', { 'forceNew': true });
socket.on('connect', () => {
console.log('Client connected...');
socket.on('new_order', (message) => {
console.log(message);
});
但不要在Docker内部使用它。