我在服务器外观的docker容器中有一个小型套接字服务器
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server,{origins: 'localhost:*'});
io.on('connection',function (socket) {
console.log('Connected');
});
const PORT = 8081;
const HOST = '0.0.0.0';
server.listen(PORT,HOST);
和docker文件是
FROM keymetrics/pm2-docker-alpine:latest
WORKDIR /root
RUN apk update && \
apk upgrade && \
apk add git
ENV HOME /root
COPY socket.js ./
COPY package.json ./
RUN npm install
COPY pm2.json ./
EXPOSE 8081
CMD [ "pm2-docker","start","pm2.json" ]
pm2.json看起来像
{
"apps": [{
"name": "socket-server","script": "socket.js","exec_mode" : "cluster","instances" : 2,"env": {
"production": true
}
}]
}
的package.json
{
"name": "socket-server","version": "1.0.0","description": "","main": "socket.js","scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},"author": "","license": "ISC","dependencies": {
"express": "^4.15.3","socket.io": "^2.0.3"
}
}
一切都运行得很好
docker run -d -p 8081:8081 socket-server
直到我尝试从另一个容器中运行的网站连接到它,网站连接如下…
并且在控制台中,它显示它可以正常轮询
Request URL:http://localhost:8081/socket.io/?
EIO=3&transport=polling&t=LthQCgI&sid=93sOyTiSOe5RVOdEAAAL
Request Method:POST
Status Code:200 OK
但无法获得套接字连接
Request URL:ws://localhost:8081/socket.io/?
EIO=3&transport=websocket&sid=93sOyTiSOe5RVOdEAAAL
Request Method:GET
Status Code:400 Bad Request
现在,如果我运行套接字服务器,而不是在docker容器中它就可以了,套接字就连接了.
我已经尝试获取套接字服务器正在运行的容器的IP并在连接脚本中使用它,但是当我像这样配置时,甚至轮询也不起作用.
我真的需要在Docker容器中.
任何帮助都非常感谢
最佳答案
也许你应该尝试建立一个docker swarm并让容器加入同一个网络:
....
version: '3.5'
services:
myserver:
image: 'mydocker-image'
networks:
- mynetwork
....
并像这样访问http://myserver:8081服务器