Without dockerizing the application, everything works properly.
When migrating the application to Docker, I am unable to to receive socket events in the browser.
I am able to receive socket events in the server, from the browser and console.
docker-compose.yml
database:
image: mongo:latest
container_name: minipool_database
ports:
- "27017:27017"
seed:
build: seed
container_name: mp_seed
links:
- database
application: (Node v.7.9.0 / socket-io: 1.4.8 / Angular 1.4.9 / angular-socket-io: 0.7.0)
build: application
container_name: mp_application
links:
- database
ports:
- "8080:8080"
Express server
'use strict';
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var connection = '';
if(process.env.NODE_ENV === 'development') connection = '127.0.0.1:27017/minipool';
if(process.env.NODE_ENV === 'production') connection = 'database:27017/minipool';
var express = require('express'),
app = express(),
server = require('http').Server(app),
io = require('socket.io')(server);
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
next()
});
app.use(express.static('./'));
app.use(function(req,res,next){
req.io = io;
next();
});
server.listen(8080, function() {});
io.on('connection', function(socket){
var User = require('./api/model/api.model.user');
var user_id = '';
// Update socket id on connection
socket.on('join', function(data){
user_id = data._id;
// Save socket.id on load
});
});
index.html
script(src='/socket.io/socket.io.js')
angular-socket-io
var socket = options.ioSocket || io.connect();
I knew the way I was passing the socket reference was off, a good example of how something can minimally work.
Passing the socket reference in the request here:
app.use(function(req,res,next){
req.io = io;
next();
});
Can be done properly in Express 4:
app.set('socketio', io);
Referenced in a route:
exports.index = function(req, res) {
var io = req.app.get('socketio');
io.to(user.sockets[j]).emit("game-update", {
game: game
});
});
Sockets are working in Docker containers now.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.