Use Node. js + Mongodb to build a CloudFoundry-based project

Source: Internet
Author: User
Tags cloud computing platforms install mongodb mongodb version
With the rise of cloud computing, many vendors have launched their own cloud computing platforms, such as VMware, Amazon, Google, and Microsoft. This article will introduce the cloud computing platform of VMware-CloudFoundry. This article will use Node. js + MongoDB to build CloudFoundry-based... SyntaxHi

With the rise of cloud computing, many vendors have launched their own cloud computing platforms, such as VMware, Amazon, Google, and Microsoft.

This article introduces Cloud Foundry, a Cloud computing platform of VMware, and uses Node. js + MongoDB to build a Cloud Foundry-based project.

Required knowledge:

Use of Node. js and NPM command lines.

Node. js syntax.

MongoDB syntax.

Mongoose syntax.

Environment setup:

Windows 7

Node. js + Ruby + vmc (Cloud Foundry cel command line tool)

User level and difficulty:

All users

Moderate

This article will learn:

Master the environment configuration of Node. js, Ruby, DevKit, and vmc.

Connect to the Cloud Foundry remote database (MongoDB) using tunnel.

Node. js Configuration:

Configuration:

Download the corresponding node. js installation package based on the actual situation. (The selected version should be consistent with the Node. js environment of Cloud Foundry)

Because the msi solution is used, double-click the downloaded installation package.

Restart the system.

Verification:

In cmd, type node-v/npm-v. If the corresponding version number is displayed, the installation is successful.

Ruby Configuration:

The Cloud Foundry operation is based on vmc, which requires the Ruby environment before installing vmc.

Because Devkit is required, the Ruby version here is 1.9.2. (1.9.3 there is a problem with DevKit)

Configuration:

Decompress it to any folder, such as: {drive letter}: \ DevTools \ ruby-1.9.2-p290.

Add:

RUBY_HOME = {drive letter}: \ DevTools \ ruby-1.9.2-p290

Path + = % RUBY_HOME % \ bin (the system environment variable must be configured, not the user environment variable)

Restart the system.

Verification:

In cmd, type ruby-v/gem-v. if the version number is displayed, the installation is successful.

Installation of vmc:

Installation:

Install vmc using gem, and type gem install vmc in cmd. (No restart required)

Verification:

Type vmc-v in cmd. if the version number is displayed, the installation is successful.

Use of vmc:

Establish a connection:

Vmc target api.cloudfoundry.com (specify the Cloud Foundry API address)

Create an account:

Create an account at http://www.cloudfoundry.com.

Create through vmc, and type vmc add-user [-- email, -- passwd] in cmd.

Login:

In cmd, type vmc login (enter the email address and password at registration as prompted)

Create an app (Node. js ):

Create a folder locally, for example, {drive letter }:\ nodejs \ local \ testcf

Go to the testcf root directory, and type npm install express in cmd.

Add the index. js file in the testcf folder and enter the following content:

Var express = require ('express ');
Var app = express ();
App. get ('/', function (req, res ){
Res. send ('Hello from Cloud Foundry ');
});
App. listen (process. env. VMC_APP_PORT | 3000 );
Console. log ("Server start up! ");
Local test:

Go to the testcf root directory, and type node index. js in cmd.

"Server start up!" appears on the console !" Then, enter http: // loaclhost: 3000 in the browser. If "Hello from Cloud Foundry" is displayed, the operation is successful.

Upload the App to Cloud Foundry:

Go to the testcf root directory and type vmc push -- runtime = node08 in cmd to generate the following content:

Wocould you like to deploy from the current directory? [Yn]: y
Application Name: ks-test-cf
Detected a Node. js Application, is this correct? [Yn]: y
The Application Deployed URL [ks-test-cf.cloudfoundry.com]:
Memory reservation (128 M, 256 M, 512 M, 1G, 2G) [64 M]: 128
How many instances? [1]: 1
Bind existing services to 'ks-test-cf '? [YN]: n
Create services to bind to 'ks-test-cf '? [YN]: n
Wocould you like to save this configuration? [YN]: y
Manifest written to manifest. yml.
Creating Application: OK
Uploading Application:
Checking for available resources: OK
Processing resources: OK
Packing application: OK
Uploading (22 K): OK
Push Status: OK
Staging Application 'ks-test-cf ': OK
Starting Application 'ks-test-cf ': OK
Note: The above English is relatively simple and the translation is skipped. Because the current project does not use databases
No Binding or Create Service is required.

In the browser, enter http://ks-test-cf.cloudfoundry.com/, as shown in Figure hello from Cloud Foundry. This indicates that the operation is successful. (Same as running locally)

MongoDB Configuration:

Configuration:

Download the corresponding MongoDB compressed package according to the actual situation.
Note: Because the MongoDB version corresponding to Cloud Foundry is 2.0, avoid inconsistency between the local test environment and Cloud Foundry. Select the corresponding version whenever possible.

Decompress it to any folder, such as: {drive letter}: \ DevTools \ mongodb-2.0.7.

Add:

Export db_home = {drive letter}: \ DevTools \ mongodb-2.0.7

Path + = % MONGODB_HOME % \ bin

Restart the system.

Verification:

In cmd, type mongo -- version. if the version number is displayed, the installation is successful.

Usage:

Create a local folder, for example, {drive letter}: \ mongodb \ testdb.

In cmd, enter mongod -- dbpath {drive letter}: \ mongodb \ testdb to connect to the local database.

Note: You can use clients such as MongoVUE to operate MongoDB.

Mongoose Configuration:

Mongoose is a third-party Noe. js module that allows you to operate MongoDB more conveniently.

Download:

In cmd, type npm install mongoose.

Verification: (if similar content appears, the installation is successful)


Note:

Mongoose depends on mongodb (Node. js module) during installation)

If the mongodb module is not installed, mongoose will automatically install it, as shown in.

Install mongodb independently. In cmd, enter npm install mongodb (note that the npm version must be later than 1.1.19; otherwise, an error will occur)

Node. js connects to MongoDB :( Localhost Local Mode)

Mongoose introduction:

Var db = require ('mongoose ');
Define an Object structure: (To work with Cloud Foundry)

Mongo = {
'Hostname': 'localhost ',
& Apos; port: 27017,
'Username ':'',
'Password ':'',
'Db': testdb
}
Note: three attributes are hostname, port, and db. (Corresponding to your development environment)

Generate the URL string when mongoose connects to mongodb:

Var generate_cmd_url = function (mongo ){
Return 'mongodb: // '+ mongo. hostname +': '+ mongo. port +'/'+ mongo. db;
}
Connect to a database (MongoDB ):

Db. connect (Response URL );
Create a Schame and a model:

Var Schema = db. Schema,
ObjectId = Schema. ObjectId;
Var testSchema = new Schema ({
Host: String,
Dbs: String,
Time: Date
});
Binding model:

Var TestModule = db. model ('test-cloudfoundry ', testSchema );
Note: test-cloudfoundry is the Collection name (Collection is equivalent to the SQL Table concept)

Save data to Collection:

Var test = new TestModule ();
Test. host = mongo. hostname;
Test. dbs = mongo. db;
Test. time = new Date ();
Test. save (function (err ){
If (! Err ){
Console. log ('Save complete ')
}
Else {
Console. log ('Save error = '+ err)
}
});
Note: The save method is equivalent to the SQL Insert statement, and Mongoose also defines the callback function.
For use.

Run:

Use mongod -- dbpath to connect to the local MongoDB.

Go to the test-cf root directory and type node index. js in cmd.

Access http: // localhost: 3000/in the browser. If the following content appears in cmd, it indicates that MongoDB is successfully called.

Mongodb url: mongodb: // localhost: 2701
/TestdbServer start at http: // localhost: 3000
Save complete
Note:

The mongo variable does not need to be defined as an Object type, but is only processed in concert with Cloud Foundry.

Mongoose's unique Schame mechanism corresponds to the Table data structure.

Connect to the Cloud Foundry remote database:

Installation:

Gem install eventmachine -- pre

Gem install caldecott (if an exception or the following error occurs, install DevKit. Otherwise, skip this section)

Please update your PATH to include build tools or download the DevKit
From 'HTTP: // rubyinstaller.org/downloads' and follow the instruction
At 'HTTP: // github.com/oneclick/rubyinstaller/wiki/Development-Kit'
DevKit installation:

Configuration:

Decompress to any folder, such as {drive letter}: \ DevTools \ devkit-4.5.2

Go to the devkit-4.5.2 root directory and type: ruby dk. rb init in cmd

After the installation is correct, the config. yml file is generated, edit the file, and type the directory where ruby is located, in the format of-{drive letter}:/DevTools/ruby-1.9.2-p290 (pay attention to the position, slash)

Ruby dk. rb review (check whether the list of Ruby supported by DevKit is correct. skip this step)

Ruby dk. rb install

Verification:

Gem install caldecott

If no error message is displayed, the installation is successful.

Note:

DevKit version: DevKit-tdm-32-4.5.2-20111229-1559-sfx.exe

Ruby version of DevKit-tdm-32-4.5.2-20111229-1559-sfx.exe: 1.9.2-p290

Note: The matching of the above versions has been verified, and other versions have not been verified.

Node. js: (Cloud Foundry remote connection)

Create a MongoDB Service:

Vmc create-service mongodb testdb

Bind Service to App (ks-test-cf ):

Vmc bind-service testdb ks-test-cf
Note: testdb is the MongoDB just created; ks-test-cf is the App Name uploaded (push.

Modify the connection between Node. js and local MongoDB:

Modify the mongo variable:

If (process. env. VCAP_SERVICES ){
Var env = JSON. parse (process. env. VCAP_SERVICES );
Mongo = env ['mongodb-2.0 '] [0] ['credentials'];
}
Else {
Mongo = {
'Hostname': 'localhost ',
& Apos; port: 27017,
'Username ':'',
'Password ':'',
'Db': 'testdb'
}
}
Note: The logic for determining the current environment is added. process. env. VCAP_SERVICES is Node. js.
Provided system variables (JSON), saving the current login to the Cloud Foundry App
(Ks-test-cf.

Modify the generate_mongo_url method:
Var generate_cmd_url = function (obj ){
If (process. env. VCAP_SERVICES ){
Return 'mongodb: // '+ obj. username + ':' + obj. password + '@' + obj. hostname + ':' + obj. port + '/' + obj. db;
}
Else {
Return 'mongodb: // '+ obj. hostname +': '+ obj. port +'/'+ obj. db;
}
}
Note: When the current environment is Cloud Foundry, The mongodb string generation logic is added,
Username and password are added to the local connection url.

Update:

Go to the testcf root directory and type vmc update ks-test-cf in cmd. If the following content appears, the update is successful:

Uploading Application:
Checking for available resources: OK
Processing resources: OK
Packing application: OK
Uploading (26 K): OK
Push Status: OK
Stopping Application 'ks-test-cf ': OK
Staging Application 'ks-test-cf ': OK
Starting Application 'ks-test-cf ': OK
Run:

In the browser, type: http://ks-test-cf.cloudfoundry.com/

In cmd, type vmc logs ks-test-cf to view the background printing information of ks-test-cf)

Server start up!
Mongodb url: mongodb:/XXXXXXXXXXX: XXXXXXXXXXX@172.30.48.68: 25176/db
Server start at http: // 172.30.50.21: 12265
Save complete
Remotely connect to the Cloud Foundry Database (testdb ):

Type vmc tunnel testdb in cmd and the following content will appear:

Binding Service [testdb]: OK
Stopping Application 'callot': OK
Staging Application 'callot': OK
Starting Application 'callot': OK
Getting tunnel connection info: OK
Service connection info:
Username: XXXXXXXXXXX
Password: XXXXXXXXXXX
Name: db
Url: mongodb: // XXXXXXXXXXX: XXXXXXXXXXX@172.30.48.68: 25176/db

Starting tunnel to testdb on port 10000.
1: none
2: mongo
3: mongodump
4: mongorestore

Which client wocould you like to start
Note: The username and password are generated by the Cloud Foundry system.
Go. Select 1 to use a local client to connect to the Vue, as mentioned earlier.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.