`

Install MongoDB、Node.js on CentOS (ECS of AliYun Cloud)

阅读更多

 

----------------------install Node.js (from AliYun)-----------------------------------

//下载Node.js安装包
>wget https://nodejs.org/dist/v6.9.5/node-v6.9.5-linux-x64.tar.xz
//解压文件
>tar xvf node-v6.9.5-linux-x64.tar.xz
//创建软链接,您就可以在任意目录下直接使用node和npm命令
>ln -s /root/node-v6.9.5-linux-x64/bin/node /usr/local/bin/node
>ln -s /root/node-v6.9.5-linux-x64/bin/npm /usr/local/bin/npm
//查看node、npm版本
>node -v
>npm -v
//至此,Node.js环境已安装完毕。软件默认安装在/root/node-v6.9.5-linux-x64/目录下。
//如果需要将该软件安装到其他目录(例如:/opt/node/)下,请进行如下操作:
>mkdir -p /opt/node/
>mv /root/node-v6.9.5-linux-x64/* /opt/node/
>rm -f /usr/local/bin/node
>rm -f /usr/local/bin/npm
>ln -s /opt/node/bin/node /usr/local/bin/node
>ln -s /opt/node/bin/npm /usr/local/bin/npm

//使用Node.js的版本管理软件NVM安装(适用于长期做node开发的人员或有快速更新node版本、快速切换node版本的场景)
//使用git将源码克隆到本地的~/.nvm目录下,并检查最新版本
>yum install git
git clone https://github.com/cnpm/nvm.git ~/.nvm && cd ~/.nvm && git checkout `git describe --abbrev=0 --tags`
//激活NVM
>echo ". ~/.nvm/nvm.sh" >> /etc/profile
source /etc/profile
//列出Node.js的所有版本
>nvm list-remote
//安装多个Node.js版本
>nvm install v6.9.5
>nvm install v7.4.0
//运行nvm ls查看已安装的Node.js版本,当前使用的版本为v7.4.0。返回结果如下所示。
[root@iZXXXXZ .nvm]# nvm ls
      v6.9.5
->       v7.4.0
      system
stable -> 7.4 (-> v7.4.0) (default)
unstable -> 6.9 (-> v6.9.5) (default)
//运行nvm use v7.4.0切换Node.js版本至v7.4.0。返回结果如下所示。
[root@iZXXXXZ .nvm]# nvm use v7.4.0
Now using node v7.4.0

  

Node 技术栈是由全局可用的功能,核心模块和社区创建的模块组成,由后往前产生依赖:

Node 核心(V8、libev、libeio)、核心模块(http、net ...)、社区创建模块。

 

NPM 访问社区附加组件或包,如寻找一个 XML 生成器:

$ npm search xml generator

其次还可以使用 web 搜索

 

应用中的 package.json 可用来管理依赖,package.json 文件包含 NPM 获取和运行应用程序所需的所有内容,它包括名称、版本、描述,初始执行文件、生产依赖,开发依赖、支持的 Node 版本等等。

添加依赖项:

 

//首先为新应用创建一个目录,并进入它
$ mkdir myapp
$ cd myapp

//使用 NPM 的 init 命令为应用创建一个 package.json 文件,该命令将请求一系列的信息,包括应用的名称和版本,程序初始进入点的文件名(默认为 index.js)
$ npm init

//接下来在 myapp 目录中安装 Express,用下面的命令将 Express 保存在 package.json 文件中的依赖表里:
$ npm install express

//index.js 中可以调用 require() 函数来使用库:
const express = require('express');
const app = express();

app.get('/', (req, res) => {
res.send('Hello World!')
});

app.listen(3000, () => {
console.log('示例程序正在监听 3000 端口!')
});


//启动服务器
$ node index.js
示例程序正在监听 3000 端口!

//在浏览器中访问 http://127.0.0.1:3000/

 

 如果一个依赖只在开发过程中用到,应该将其保存为“开发依赖”:

 

//包用户便无需在生产环境中安装它们,当前应用的 package.json 文件中将自动添加以下 test 项目:
$ npm install test --save-dev

 

npm  的局部安装和全局安装:

 

#局部安装将下载模块放到当前工作目录的 node_moudle 文件下,若不存在 npm 会创建。
$ npm install express
#全局安装将下载模块放在 /usr/local 目录下(非win系统)。
$npm install -g express
#查看包文档
$npm docs express
#检查包的源码
$npm explore express (将工作目录设定为包源码的顶层目录)
$npm -g explore express (探索全局安装包的源码)

 

 

以上默认官方镜像安装是很慢的,推荐使用以下镜像进行安装:

临时使用

npm --registry https://registry.npm.taobao.org install express

长期使用

npm config set registry https://registry.npm.taobao.org
//验证是否成功
npm config get registry
//or
npm info express

  

使用 Express 应用生成器可以生成一个应用框架:

$ npm install express-generator -g
//如果默认官方镜像比较慢,可以使用 taobao 镜像
$ npm --registry https://registry.npm.taobao.org install express-generator -g

//创建一个 myapp 的应用,NPM 将在当前位置的子目录中创建新的 Express 应用
$ express myapp
//新应用根目录的 package.json 文件可以看看安装的依赖项

$cd myapp
//为 myapp 安装所有依赖
$npm install
//运行应用,DEBUG 命令可以展示应用运行时返回的有用的日志信息
$ DEBUG=helloworld:* npm start

//打开浏览器并访问 http://127.0.0.1:3000/ 将看到 Express 的默认欢迎页面。

 win10 上启动采用:

> set DEBUG=myapp & npm start

 

 

 然后就可以进行部署测试:

部署测试

1.新建项目文件example.js
>cd ~
>touch example.js

2.修改项目文件example.js
>vim example.js
//编辑模式将以下项目文件内容粘贴到文件中保存并关闭
const http = require('http');
const hostname = '0.0.0.0';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});

server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});

3.运行项目
>node ~/example.js

4.运行以下命令查看是否在监听项目端口,返回的结果列表中包含端口3000,表明项目正常运行
>netstat -tpln

5.登录ECS管理控制台,并在ECS实例安全组的入方向添加规则, 放行项目中配置的端口(本示例中端口号为3000)。

6.在本地机器的浏览器中输入http://<ECS实例公网IP地址>:端口号访问项目。

 

创建站点框架:

如何使用 Express 应用生成器创建一个可添加路由、模板/视图和数据库调用的“骨架”网站。

可以直接运行 express 命令,将使用 Jade 视图引擎和纯 CSS 在当前目录中创建项目。如果指定目录名,则在子目录中创建项目。 

 

//express 命令将使用 Jade 视图引擎和纯 CSS 在当前目录中创建项目
$ express
//还可以使用 --view 选择视图(模板)引擎,并且/或者使用 --css 选择 CSS 生成引擎。

//Express 应用生成器支持多款流行的视图/模板引擎,包括 EJS、Hbs、Pug (Jade)、Twig 和 Vash,缺省选项是 Jade。此处选用 Pug 模板引擎,Jade 是其前身。
$ express myyapp --view=pug

//Express 应用生成器支持最常见的 CSS 引擎:LESS, SASS, Compass, Stylus。


//运行骨架网站
//安装依赖项(install 命令将获取项目的 package.json 文件中列出的所有依赖项包)
$ npm install

//运行该应用,直接通过 npm start 命令启动应用也可以,但不会看到调试信息。
$ DEBUG=myapp:* npm start

//在浏览器中访问 http://localhost:3000/

 

如果 设置过 nodemon 自动重启工具,则可以使用:

$ DEBUG=myapp:* npm run devstart

 

 

 

文件改动时重启服务器

只有重启服务器才能看到 Express 网站所做的改动。使用 nodemon 工具将手动启停服务器改成自动化:

写道
$ sudo npm install -g nodemon
//还可以把它作为开发依赖将安装在本地,使用该项目的开发人员只要安装该应用就能自动获得
$ npm install --save-dev nodemon
//项目的 package.json 文件将自动添加一个新的属性
"devDependencies": {
"nodemon": "^1.18.9"
}

//安装好依赖项的生成项目具有如下文件结构
/express-locallibrary-tutorial
app.js
/bin
www
package.json
/node_modules
/public
/images
/javascripts
/stylesheets
style.css
/routes
index.js
users.js
/views
error.pug
index.pug
layout.pug

package.json 文件定义依赖项和其他信息,以及一个调用应用入口(/bin/www,一个 JavaScript 文件)的启动脚本,脚本中还设置了一些应用的错误处理,加载 app.js 来完成其余工作。
/routes 目录中用不同模块保存应用路由。
/views 目录保存模板。

"scripts" 部分,定义了一个 "start" 脚本,当运行 npm start 时会调用它来启动服务器。在脚本定义中可以看到 start 实际上运行了 "node ./bin/www"。

文件 /bin/www 是应用入口!它做的第一件事是 require() “真实” 的应用入口(即项目根目录中的 app.js ),app.js 会设置并返回 express() 应用对象。文件的其余部分先为 app 设置端口(环境变量中的预定义值或默认值 3000),再创建一个 HTTP 服务器,然后开始监听请求,报告服务器错误和连接信息。

app.js 文件创建一个 express 应用对象(依照惯例命名为 app),通过各种设置选项和中间件来设置这个应用,然后从该模块中导出。上文的 www 入口文件中 require() 的 app 就是这里导出的 。
var express = require('express');
var app = express();
...
module.exports = app;
首先,它使用 require() 导入了一些实用 node 库,其中包括之前用 NPM 下载的 express,http-errors,morgan 和 cookie-parser,还有一个 path 库,它是用于解析文件和目录的核心 node 库。
var express = require('express');
var createError = require('http-errors');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var path = require('path');
然后 require() 的是用户路由目录中的模块。这些模块/文件用于处理特定的“路由”(URL 路径)。可以通过添加新文件来扩展骨架应用。
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
下面我们用导入的 express 模块来创建 app 对象,然后使用它来设置视图(模板)引擎。设置引擎分两步:首先设置 'views' 以指定模板的存储文件夹(此处设为子文件夹 /views)。然后设置 'view engine' 以指定模板库(本例中设为 “pug” )。
var app = express();
// view engine setup
// 视图引擎设定
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
下一组 app.use() 调用将中间件库添加进请求处理链。除了之前导入的第三方库之外,我们还使用 express.static 中间件将项目根目录下所有静态文件托管至 /public 目录。
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
最后一个中间件为错误和 HTTP 404 响应添加处理方法。
Express 应用对象(app)现已完成配置。最后一步是将其添加到 exports 模块(使它可以通过 /bin/www 导入)。
module.exports = app;

路由文档 /routes/users.js 首先加载 express 模块​​并获取 express.Router 对象(命名为 router)。然后为 router 指定路由,最后导出 router(就可以导入 app.js 了)。
var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});

module.exports = router;
该路由定义了一个回调,在检测到正确模式的 HTTP GET 请求时将调用该回调。正确模式即导入模块时指定的路由('/users')加该模块('/')中定义的任何内容。换句话说,在收到 /users/ URL 时使用此路由。上述回调函数有第三个参数 'next',因此它是一个中间件函数,而不是简单的路由回调。next 参数暂时还用不到,在 '/' 路径中添加多个路由处理器时才会涉及。

视图(模板)存保存在 /views 目录中( app.js 中指定),使用 .pug / .jade 扩展名。 Response.render() 方法用某对象的某个变量值一同来渲染一个特定的模板,然后将结果作为响应发送。在 /routes/index.js 中可以看到,该路由使用 'index' 模板和一个模板变量 title 来渲染响应。
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
title 变量将以 'Express' 作为值插入模板的指定位置。
extends layout
block content
h1= title
p Welcome to #{title}

 

 可以使用CURL验证测试效果

 

//新开一个Terminal并输入以下可以在 node 服务器运行窗口看到效果
curl -X GET http://localhost:8080

//设置HTTP参数为POST/PUT,为传入数据设置Content-Type并发送数据
//使用-H参数指定curl中的HTTP请求头
curl -s -X POST -H "Content-Type:application/json" \ -d '{"album_name":"new album name"}' \ http://localhost:8080/albums/rename.json

 

 

 

 

 

 

 


 --------------------------------------------install mongoDB-----------------------------------------------------------

MongoDB provides officially supported packages in their own repository:

mongodb-org metapackage that will automatically install the four component packages listed below.
mongodb-org-server Contains the mongod daemon, associated init script, and a configuration file(/etc/mongod.conf). You can use the initialization script to start mongod with the configuration file. For details, see Run MongoDB Community Edition.
mongodb-org-mongos Contains the mongos daemon.
mongodb-org-shell Contains the mongo shell.
mongodb-org-tools Contains the following MongoDB tools: mongoimport bsondumpmongodumpmongoexportmongofilesmongorestoremongostat, and mongotop.

 

 

//1.Configure the package management system (yum).
//Create a /etc/yum.repos.d/mongodb-org-4.2.repo file so that you can install MongoDB directly using yum:
[mongodb-org-4.2]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.2/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.2.asc

//2.Install the MongoDB packages
>sudo yum install -y mongodb-org
//Alternatively, to install a specific release of MongoDB, specify each component package individually and append the version number to the package name, as in the following example:
>sudo yum install -y mongodb-org-4.2.2 mongodb-org-server-4.2.2 mongodb-org-shell-4.2.2 mongodb-org-mongos-4.2.2 mongodb-org-tools-4.2.2
//You can specify any available version of MongoDB. However yum upgrades the packages when a newer version becomes available. To prevent unintended upgrades, pin the package. To pin a package, add the following exclude directive to your /etc/yum.conf file:
exclude=mongodb-org,mongodb-org-server,mongodb-org-shell,mongodb-org-mongos,mongodb-org-tools

//3.Run MongoDB (To Use Default Directories)
By default, MongoDB runs using the mongod user account and uses the following default directories:
/var/lib/mongo (the data directory)
/var/log/mongodb (the log directory)
If you installed via the package manager, The default directories are created, and the owner and group for these directories are set to mongod.
If you installed by downloading the tarballs,The default MongoDB directories are not created. To create the MongoDB data and log directories:
>mkdir -p /var/lib/mongo
>mkdir -p /var/log/mongodb
By default, MongoDB runs using the mongod user account. Once created, set the owner and group of these directories to mongod:
>chown -R mongod:mongod <directory>

//4. Start MongoDB
>sudo service mongod start
You can verify that the mongod process has started successfully by checking the contents of the log file at /var/log/mongodb/mongod.log for a line reading:[initandlisten] waiting for connections on port <port>
where <port> is the port configured in /etc/mongod.conf, 27017 by default.
You can optionally ensure that MongoDB will start following a system reboot by issuing the following command:
>systemctl enable mongod.service

//stop
As needed, you can stop the mongod process by issuing the following command:
>systemctl stop mongod.service

//restart
You can restart the mongod process by issuing the following command:
>systemctl restart mongod.service
You can follow the state of the process for errors or important messages by watching the output in the /var/log/mongodb/mongod.log file.

//begin
Start a mongo shell on the same host machine as the mongod. You can run the mongo shell without any command-line options to connect to a mongod that is running on your localhost with default port 27017:
>mongo

//uninstall
//Stop the mongod process by issuing the following command:
>sudo service mongod stop
//Remove any MongoDB packages that you had previously installed.
>sudo yum erase $(rpm -qa | grep mongodb-org)
//Remove MongoDB databases and log files.
>sudo rm -r /var/log/mongodb
>sudo rm -r /var/lib/mongo

 

 

//check the available version of MongoDB
> yum info mongodb-org

//Verifying MongoDB Installation
> mongo
or MongoDB shell type enter : $ db.version()
Once you are inside the MongoDB shell type the following command to connect to the admin database:
> use admin
output:switched to db admin
Create a new user named mongoAdmin with the userAdminAnyDatabase role:
> db.createUser(
  {
    user: "mongoAdmin", 
    pwd: "changeMe", 
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)
Exit the mongo shell with:
> quit()

//check the installed MongoDB version
> mongo --version

//Set MongoDB as system Service
> systemctl enable mongod

//how to use mongo command and check its operation
Let’s create a database – db01
> mongo db01
Create a collection to insert some demo data into it:
> db.createCollection('users');
Add documents to the collection. 
> db.users.insert( {name:"micheal", age:27} );
Gets the documents in the collection.
> db.users.find();
output:{ "_id" : ObjectId("5d948001181f1b56bb74e854"), "name" : "micheal", "age" : 27 }
let’s find out the collection with a particular age that is 27.
> db.users.find( {age:27} );
Output: { "_id" : ObjectId("5d948001181f1b56bb74e854"), "name" : "micheal", "age" : 27 }

 

  • 大小: 170.1 KB
  • 大小: 125.3 KB
  • 大小: 16.2 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics