我使用Bluemix实验性mongoDB服务和节点运行时在Cloud Foundry上运行了一个基本的Node.js应用程序。
我愿意将应用程序停靠。在我的计算机上本地工作正常(应用程序的一个容器和使用官方mongo映像的Mongo的一个容器)。但是我有问题要在Bluemix云上运行它。
我已经使用绑定的mongoDB实验服务和命令行创建了一个云代工桥应用程序
cf ic run --name mytodolist -e CCS_BIND_APP = bridgeapp000 IMAGE_NAME
Container已成功创建,我可以访问该应用程序,但该应用程序无法连接到数据库。这里是我得到的应用程序日志:
Using the experimental service and uri is mongodb://70b7204a-3607-474d-ac81-34fdb638d714:ac44ef2d-87ee-48aa-bbee-3d08a18459c4@23.246.199.107:10137/db
dbURI is: mongodb://70b7204a-3607-474d-ac81-34fdb638d714:ac44ef2d-87ee-48aa-bbee-3d08a18459c4@23.246.199.107:10137/db
connecting
App listening on port 8080
mongodb://70b7204a-3607-474d-ac81-34fdb638d714:ac44ef2d-87ee-48aa-bbee-3d08a18459c4@23.246.199.107:10137/db
disconnected
dbURI is: mongodb://70b7204a-3607-474d-ac81-34fdb638d714:ac44ef2d-87ee-48aa-bbee-3d08a18459c4@23.246.199.107:10137/db
connecting
Error in MongoDb connection: Error: failed to connect to [23.246.199.107:10137]
disconnected
dbURI is: mongodb://70b7204a-3607-474d-ac81-34fdb638d714:ac44ef2d-87ee-48aa-bbee-3d08a18459c4@23.246.199.107:10137/db
connecting
Error in MongoDb connection: [object Object]
请注意,在我的Dockerfile中,我在启动节点服务器之前添加了一个sleep函数。
CMD睡眠60&& node server.js
知道问题可能来自哪里?可能是Bluemix上的Docker容器无法访问实验服务吗?
有关信息,这里是我用来检索数据库URI的代码:
// MongoDB - connection URI
if(process.env.VCAP_SERVICES){
var services = JSON.parse(process.env.VCAP_SERVICES);
if(services['mongolab']) {
var uri = services['mongolab'][0].credentials.uri;
}
if(services['mongodb-2.4']){
var uri = services['mongodb-2.4'][0].credentials.url;
console.log("Using the experimental service and uri is "+uri);
}
} else {
if (process.env.DB_PORT_27017_TCP_ADDR){
uri = "mongodb://" + process.env.DB_PORT_27017_TCP_ADDR + ":" + process.env.DB_PORT_27017_TCP_PORT +"/docker";
} else{
uri = ""
}
}
module.exports = {
url: uri
};
以及与数据库建立连接的代码:
var db = mongoose.connection;
db.on('connecting', function() {
console.log('connecting');
});
db.on('error', function(error) {
console.error('Error in MongoDb connection: ' + error);
mongoose.disconnect();
});
db.on('connected', function() {
console.log('connected!');
});
db.once('open', function() {
console.log('connection open');
});
db.on('reconnected', function () {
console.log('reconnected');
});
db.on('disconnected', function() {
console.log('disconnected');
console.log('dbURI is: '+database.url);
mongoose.connect(database.url, {server:{auto_reconnect:true, socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 }}, replset: { socketOptions: { keepAlive: 1, connectTimeoutMS : 30000 } }});
});
console.log('dbURI is: '+ database.url);
mongoose.connect(database.url, {server:{auto_reconnect:true}});