【发布时间】:2019-02-04 15:04:05
【问题描述】:
我在 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
直到我尝试从在另一个容器中运行的网站连接到它,网站才会像这样连接......
<script src="socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8081');
socket.on('connect', function(data) {
console.log('Connected Client')
});
</script>
在控制台中,它显示它的轮询很好
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 容器中使用它。
非常感谢任何帮助
【问题讨论】: