vue+node項目部署上線

在線地址: cl8023.com github

程序員詞彙學習網: www.english4coder.comhtml

雲服務器

阿里雲 or 騰訊雲

  • 阿里雲服務器品牌:ECS(Elastic Compute Service)
  • 騰訊雲服務器品牌:VCM(Cloud Virtual Machine)

騰訊雲or阿里雲

二者均可以,具體能夠根據本身的需求,都說阿里雲穩定,騰訊雲便宜,我本身買時發現二者入門級的價格都差很少,就買了阿里雲的,如下即以阿里雲的服務器操做。(騰訊雲服務器操做應該也相似)前端

購買阿里雲服務器ECS

入門級最低配便可,一年300多,每個月幾十塊錢,也能夠月付,那樣就貴點。

中間有些選項默認就可,鏡像選擇 公共鏡像-CentOS-7.4 64位(最新的)
圖中密碼用來以後遠程登錄服務器使用。vue

登錄服務器

阿里網頁登錄

在 管理控制檯-實例 中能夠看到剛剛購買的服務器

點擊遠程鏈接,出現登錄界面,第一次進入會彈出一個密碼,記住這個密碼(只會出現一次),以後登錄輸入這個密碼便可進入阿里雲服務器ECS系統。node

客戶端工具遠程登錄

  1. Mac

終端中輸入:SSH root@服務器IP地址(公) (SSH root@192.18.222.12)
回車
輸入購買服務器時設置的實例密碼便可mysql

  1. Windows
  • 下載工具 Xshell
  • 打開Xshell - 文件 - 新建,終端選項選擇編碼:Unicode(UTF-8)

  • 鏈接成功

配置環境

Linux 經常使用命令:linux

  1. wget:一個從網絡上自動下載文件的自由工具,支持經過 HTTP、HTTPS、FTP 三個最多見的 TCP/IP協議 下載,並可使用 HTTP 代理。"wget" 這個名稱來源於 「World Wide Web」 與 「get」 的結合。
  2. tar:壓縮解壓命令nginx

    • -c:創建壓縮檔案
    • -x:解壓
    • -t:查看內容
    • -r:向壓縮歸檔文件末尾追加文件
    • -u:更新原壓縮包中的文件

這五個是獨立的命令,壓縮解壓都要用到其中一個,能夠和別的命令連用但只能用其中一個。下面的參數是根據須要在壓縮或解壓檔案時可選的。c++

- -z:有gzip屬性的
- -j:有bz2屬性的
- -Z:有compress屬性的
- -v:顯示全部過程
- -O:將文件解開到標準輸出
下面的參數 -f 是必須的
- -f:使用檔案名稱,最後一個參數,後面只能接檔案名
  1. ln:爲某一個文件或目錄在另外一個位置創建一個同步的連接 經常使用:ln -s 源文件 目標文件
  2. makdir:建立目錄
  3. mv:爲文件或目錄更名、或將文件或目錄移入其它位置
  4. rm:刪除文件git

    • -f:忽略不存在的文件,從不給出提示
    • -r:將參數中列出的所有目錄和子目錄均遞歸的刪除
  5. yum:提供了查找、安裝、刪除某一個、一組甚至所有軟件包的命令
  6. ls:顯示當前目錄下文件, ls -f 隱藏文件也顯示
  7. netstat -tpln:查看進程端口
  8. kill -9 PID號:關閉進程
  9. cp:拷貝

Linux 目錄:
前面進入Linux系統後,通常會在 root(~) 目錄下 [root@xxxxxxxxxxx ~]# , cd ..能夠即回到根目錄,ls查看當前目錄下文件程序員

[root@xxxxxxxxxxx ~]#
[root@xxxxxxxxxxx ~]# cd ..
[root@xxxxxxxxxxx /]#
[root@xxxxxxxxxxx /]# ls
bin  boot  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@xxxxxxxxxxx /]# cd root
[root@xxxxxxxxxxx ~]#

安裝NodeJs

阿里雲幫助文檔:部署Node.js項目(CentOS)

安裝MySQL

主要參考

1. 下載安裝包

爲了下載到最新的版本,先到官網上找到下載連接
MySQL下載地址

先用瀏覽器或其餘下載工具建立下載任務(如x86,64-bit),而後在下載中找到下載連接複製下來就能夠把它刪了。

  • 進入root目錄:cd /root (也能夠其餘目錄)
  • 下載安裝包:

wget https://cdn.mysql.com//Downloads/MySQL-5.7/mysql-5.7.20-linux-glibc2.12-x86_64.tar.gz

  • 下載完成後 ls 能夠看到下載的安裝包
[root@xxxxxxxxxxx ~]# ls
mysql-5.7.20-linux-glibc2.12-x86_64.tar.gz ......

2. 解壓文件

tar -xzvf mysql-5.7.19-linux-glibc2.12-x86_64.tar.gz -C /usr/local/

[root@xxxxxxxxxxx ~]# ls
mysql-5.7.20-linux-glibc2.12-x86_64 (解壓獲得的目錄)
mysql-5.7.20-linux-glibc2.12-x86_64.tar.gz

// 拷貝解壓到目錄到 /usr/local 目錄下,並更名爲 mysql
[root@xxxxxxxxxxx ~]# cp mysql-5.7.20-linux-glibc2.12-x86_64 /usr/local/mysql -r
[root@xxxxxxxxxxx ~]# cd /usr/local/mysql
[root@xxxxxxxxxxx mysql]# ls
bin  COPYING  docs  include  lib  man  README  share  support-files

3. 添加系統mysql組和mysql用戶

[root@xxxxxxxxxxx ~]# groupadd mysql #創建一個mysql的組
[root@xxxxxxxxxxx ~]# useradd -r -g mysql mysql #創建mysql用戶,而且把用戶放到mysql組

4. 在 mysql 下添加 data 目錄

[root@xxxxxxxxxxx mysql]# mkdir data

5. 更改mysql目錄下全部的目錄及文件夾所屬組合用戶

[root@xxxxxxxxxxx mysql]# cd /usr/local/
[root@xxxxxxxxxxx local]# chown -R mysql mysql/
[root@xxxxxxxxxxx local]# chgrp -R mysql mysql/
[root@xxxxxxxxxxx local]# cd mysql/
[root@xxxxxxxxxxx mysql]# ls -l
total 56
drwxr-xr-x  2 mysql mysql  4096 Nov  9 16:00 bin
-rw-r--r--  1 mysql mysql 17987 Nov  9 16:00 COPYING
drwxr-xr-x  6 mysql mysql  4096 Nov  9 18:41 data
drwxr-xr-x  2 mysql mysql  4096 Nov  9 16:00 docs
drwxr-xr-x  3 mysql mysql  4096 Nov  9 16:01 include
drwxr-xr-x  5 mysql mysql  4096 Nov  9 16:01 lib
drwxr-xr-x  4 mysql mysql  4096 Nov  9 16:00 man
-rw-r--r--  1 mysql mysql  2478 Nov  9 16:00 README
drwxr-xr-x 28 mysql mysql  4096 Nov  9 16:00 share
drwxr-xr-x  2 mysql mysql  4096 Nov  9 18:06 support-files

6. 安裝和初始化數據庫

不少老的教程中都是運行 ./scripts/mysql_install_db --user=mysql 進行安裝,但在新版本的mysql中已經沒了 scripts 目錄,
mysql_install_db 放在了 bin 目錄下

[root@xxxxxxxxxxx mysql]# cd bin
[root@xxxxxxxxxxx bin]# ./mysqld --initialize --user=mysql --basedir=/usr/local/mysql/--datadir=/usr/local/mysql/data/


2017-11-09T09:09:52.826209Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2017-11-09T09:09:54.885578Z 0 [ERROR] Can't find error-message file '/usr/local/mysql/--datadir=/usr/local/mysql/data/share/errmsg.sys'. Check error-message file location and 'lc-messages-dir' con
figuration directive.2017-08-31T08:50:24.709286Z 0 [Warning] InnoDB: New log files created, LSN=45790
2017-11-09T09:09:55.105938Z 0 [Warning] InnoDB: Creating foreign key constraint system tables.
2017-11-09T09:09:55.218562Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: c0844cc4-c52d-11e7-b74f-00163e0ae84e.
2017-11-09T09:09:55.221300Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened.
2017-11-09T09:09:55.221784Z 1 [Note] A temporary password is generated for root@localhost: uf)qP3+C?jpJ

解決:(無視警告)

[root@xxxxxxxxxxx bin]# ./mysqld --initialize --user=mysql --basedir=/usr/local/mysql/ --datadir=/usr/local/mysql/data/ --lc_messages_dir=/usr/local/mysql/share --lc_messages=en_US

7. 配置my.cnf

進入 /usr/local/mysql/support-files/ 目錄下,查看是否存在my-default.cnf 文件,若是存在直接 copy 到 /etc/my.cnf 文件中

[root@xxxxxxxxxxx mysql]# cp -a ./support-files/my-default.cnf /etc/my.cnf

若是不存在 my-default.cnf 文件, 則在 /etc/ 目錄下建立 my.cnf

[root@xxxxxxxxxxx bin]# cd /etc
[root@xxxxxxxxxxx etc]# vim my.cnf

寫入內容

#[mysql]
#basedir=/usr/local/mysql/
#datadir=/usr/local/mysql/data/

8. 啓動服務

[root@xxxxxxxxxxx mysql]# cd bin/
[root@xxxxxxxxxxx bin]# ./mysqld_safe --user=mysql &

9. 將mysqld服務加入開機自啓動項

[root@xxxxxxxxxxx bin]# cd ../support-files
[root@xxxxxxxxxxx support-files]# cp mysql.server /etc/init.d/mysql
[root@xxxxxxxxxxx support-files]# chmod +x /etc/init.d/mysql
-- 把mysql註冊爲開機啓動的服務
[root@xxxxxxxxxxx support-files]# chkconfig --add mysql

10. 啓動服務

[root@xxxxxxxxxxx bin]# service mysql start

若報錯 ERROR! The server quit without updating PID file

[root@xxxxxxxxxxx mysql]# rm  /etc/my.cnf
rm: remove regular file '/etc/my.cnf'? y
[root@xxxxxxxxxxx mysql]# /etc/init.d/mysql start
Starting MySQL.Logging to '/usr/local/mysql/data/dbserver.err'.
 SUCCESS!
[root@xxxxxxxxxxx mysql]# service mysql start
Starting MySQL SUCCESS!

11. 登陸mysql

[root@xxxxxxxxxxx bin]# ./mysql -u root -p
密碼是第6步產生的密碼

若是出現錯誤:

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

重改密碼

[root@xxxxxxxxxxx bin]# /etc/init.d/mysql stop
[root@xxxxxxxxxxx bin]# mysqld_safe --user=mysql --skip-grant-tables --skip-networking &
[root@xxxxxxxxxxx bin]# mysql -u root mysql
mysql> UPDATE user SET Password=PASSWORD('newpassword') where USER='root';

// 上面語句若出錯,換爲
update mysql.user set authentication_string=password('newpassword') where user='root'

mysql> FLUSH PRIVILEGES;
mysql> quit

[root@xxxxxxxxxxx bin]# /etc/init.d/mysqld restart
[root@xxxxxxxxxxx bin]# mysql -uroot -p
Enter password:

mysql>

12. 設置遠程登陸權限

mysql>  grant all privileges on *.* to'root' @'%' identified by 'root';
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.06 sec)

mysql> quit
Bye

13. 進程關閉

若以上步驟中出現其餘錯誤,能夠看看 mysql 是否關閉了,先關閉端口,而後在試試

[root@xxxxxxxxxxx ~]# netstat -tpln
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1105/sshd
tcp6       0      0 :::3306                 :::*                    LISTEN      25599/mysqld
[root@xxxxxxxxxxx ~]# kill -9 25599

14. 本地鏈接數據庫

我本地使用的是 Navicat for MySQL
遠程鏈接數據庫
遠程鏈接數據庫後,建立數據表(能夠導出本地數據表,而後Navicat中導入到服務器MySQL中)

上傳文件

打包文件

項目根目錄下運行

npm run build

等待命令運行結束後,會發現目錄下多了 dist 文件夾,這個文件夾就是咱們等下要放到服務器中的。

文件傳輸

  1. 下載文件傳輸工具 Xftp
  2. 打開 Xftp 新建鏈接,相似Xshell,選項中勾選 「使用UTF-8編碼(E)」

Xftp鏈接
鏈接成功後能夠看到左側是本地文件目錄,右側是服務器文件目錄,能夠很方便的來回拖放文件。

  1. 建立目錄文件 /root/projec/myblog (目錄層級、名稱隨意,這裏我以次爲項目目錄)
  2. 將剛剛的 dist 文件夾複製到 /root/project/myblog 目錄下,前端資源就OK了
  3. 將 server 文件夾也複製到 /root/project/myblog 目錄下

初始化項目

Xshell 鏈接服務器

// 進入項目目錄
[root@izwz9e9bjg74ljcpzr7stvz ~]# cd /root/project/myblog
[root@izwz9e9bjg74ljcpzr7stvz myblog]# ls
dist server

初始化建立 package.json,這一步也能夠在本地建立編輯好後上傳到服務器目錄便可

[root@izwz9e9bjg74ljcpzr7stvz myblog]# npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (myblog) 
version: (1.0.0) 
description: 
entry point: (index.js) 
test command: 
git repository: 
keywords: 
author: 
license: (ISC) 
About to write to /root/project/test/myblog/package.json:

{
  "name": "myblog",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this ok? (yes) yes

// 所有回車便可
[root@izwz9e9bjg74ljcpzr7stvz myblog]# ls
dist  package.json  server

// 打開 package.json 編輯(也可在 Xftp 中右鍵文件編輯)
[root@izwz9e9bjg74ljcpzr7stvz myblog]# vim package.json

    {
        "name": "my-blog",
        "version": "1.0.0",
        "description": "A Vue.js project",
        "author": "ChenLiang <236338364@qq.com>",
        "private": true,
        "scripts": {
            "dev": "node build/dev-server.js",
            "start": "node build/dev-server.js",
            "build": "node build/build.js"
        },
        "dependencies": {
            "body-parser": "^1.17.2",
            "cookie-parser": "^1.4.3",
            "express": "^4.16.2",
            "express-session": "^1.15.5",
            "formidable": "^1.1.1",
            "highlight.js": "^9.12.0",
            "marked": "^0.3.6",
            "mysql": "^2.14.0",
            "node-sass": "^4.5.3",
            "node-uuid": "^1.4.8"
        },
        "engines": {
            "node": ">= 4.0.0",
            "npm": ">= 3.0.0"
        },
        "browserslist": [
            "> 1%",
            "last 2 versions",
            "not ie <= 8"
        ]
    }

保存退出,運行

[root@izwz9e9bjg74ljcpzr7stvz myblog]# npm install

安裝"dependencies"中項目運行須要的全部依賴

修改資源路徑

進入文件夾 server,打開 index.js

[root@izwz9e9bjg74ljcpzr7stvz server]# vim index.js

const routerApi = require('./router');
const path = require('path');
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
const session = require('express-session');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(session({
    secret: '8023',
    // cookie: {maxAge: 60000},
    resave: false,
    saveUninitialized: true
}));

// 部署上線時讀取靜態文件
app.use(express.static(path.join(__dirname, '../dist')));

// 後端api路由
app.use('/api', routerApi);

// 監聽端口
app.listen(80);
console.log('success listen at port:80......');

設置靜態資源路徑,並修改監聽端口爲80(HTTP端口),api.js 中文件路徑相關的也要更改成 ../dist/static.....,嫌麻煩的也能夠直接將 server 文件夾移到 dist 下就不用這麼麻煩改了。

開放 80 端口

登錄阿里雲,進入控制管理臺 -> 雲服務器 ECS -> 安全組 -> 配置規則 -> 快速建立規則
開放80端口

啓動服務

[root@izwz9e9bjg74ljcpzr7stvz server]# node index.js
success listen at port:80......

瀏覽器打開 服務器IP:80(如:263.182.35.68:80),如無心外,即正常運行訪問啦。

綁定域名

進入域名管理後臺,解析域名,添加解析
域名綁定
添加主機 @.xxx.com 能夠經過 xxx.com 直接訪問
綁定成功後,直接輸入域名便可訪問。

安裝 pm2

pm2 是一個帶有負載均衡功能的Node應用的進程管理器.

上面咱們以 node index.js 啓動了項目,當咱們退出 Xshell 時,進程就會關閉,沒法在訪問到項目,而 pm2 就是
解決這種問題的,以 pm2 啓動項目後,退出 Xshell 後依然能夠正常訪問。

// 安裝 pm2
[root@izwz9e9bjg74ljcpzr7stvz /]# npm install -g pm2

// 以 -g 全局安裝的插件都在 node 安裝目錄 bin 文件下,
[root@izwz9e9bjg74ljcpzr7stvz bin]# ls
cnpm  node  npm  npx  pm2  pm2-dev  pm2-docker  pm2-runtime

bin 下都是命令語句,爲了能夠在任何目錄均可以使用命令,咱們將此文件夾加入環境變量

  1. 查看環境變量 [root@izwz9e9bjg74ljcpzr7stvz ~]# echo $PATH
  2. 永久添加環境變量(影響全部用戶)
[root@izwz9e9bjg74ljcpzr7stvz ~]# vim /etc/profile
// 在文檔最後,添加:
# node
export NODE_HOME=/root/node-v8.9.1-linux-x64
export PATH=$PATH:$NODE_HOME/bin

保存,退出,而後運行

[root@izwz9e9bjg74ljcpzr7stvz ~]# source /etc/profile

pm2 啓動項目

[root@izwz9e9bjg74ljcpzr7stvz ~]# cd /root/project/myblog/server
// 啓動進程
[root@izwz9e9bjg74ljcpzr7stvz server]# pm2 start index.js
// 中止進程
[root@izwz9e9bjg74ljcpzr7stvz server]# pm2 stop index.js
// 查看進程
[root@izwz9e9bjg74ljcpzr7stvz server]# pm2 list

刷新頁面404

HTML5 History 模式,最後有nginx的配置。

Linux中文亂碼 (修改默認編碼)

如文件或文件夾含有中文字符時,可能會讀取亂碼,讀取不到文章,須要修改系統默認編碼
修改默認編碼

Nginx 服務器

上面咱們是直接以 node 啓動一個服務器,監聽 80 端口,這樣咱們就能夠直接以 IP 地址或域名的方式訪問,也能夠監聽其餘端口如3000,這樣咱們就得在地址後加上 : 端口號,顯然這樣很麻煩,且通常 node 程序基本不監聽 80 端口,還可能同時運行幾個 node 項目,監聽不一樣的端口,經過二級域名來分別訪問。 這裏就用到 Nginx 來實現反向代理。(node 利用 node-http-proxy 包也能夠實現反向代理,有興趣本身瞭解)

Nginx安裝

Nginx依賴下面3個包:

  1. SSL功能須要openssl庫,下載地址 http://www.openssl.org/
  2. rewrite模塊須要pcre庫,下載地址 http://www.pcre.org/
  3. gzip模塊須要zlib庫,下載地址 http://www.zlib.net/
  4. Nginx安裝包

進入任意目錄下載以上壓縮包(版本號改成最新便可):

[root@izwz9e9bjg74ljcpzr7stvz download]# wget http://www.zlib.net/zlib-1.2.11.tar.gz
[root@izwz9e9bjg74ljcpzr7stvz download]# wget https://ftp.pcre.org/pub/pcre/pcre-8.41.tar.gz
[root@izwz9e9bjg74ljcpzr7stvz download]# wget https://www.openssl.org/source/openssl-fips-2.0.16.tar.gz
[root@izwz9e9bjg74ljcpzr7stvz download]# wget http://nginx.org/download/nginx-1.13.7.tar.gz
[root@izwz9e9bjg74ljcpzr7stvz download]# ls
pcre-8.41.tar.gz   zlib-1.2.11.tar.gz
nginx-1.13.7.tar.gz  openssl-fips-2.0.16.tar.gz

解壓壓縮包:

[root@izwz9e9bjg74ljcpzr7stvz download]# tar zxvf zlib-1.2.11.tar.gz
[root@izwz9e9bjg74ljcpzr7stvz download]# tar tar zxvf pcre-8.41.tar.gz
[root@izwz9e9bjg74ljcpzr7stvz download]# tar zxvf openssl-fips-2.0.16.tar.gz
[root@izwz9e9bjg74ljcpzr7stvz download]# tar zxvf nginx-1.13.7.tar.gz

先安裝3個依賴包,分別進入各自解壓目錄

// 看清各個目錄下的是 configure 仍是 config
[root@izwz9e9bjg74ljcpzr7stvz zlib-1.2.11]# ./configuer && make && make install
[root@izwz9e9bjg74ljcpzr7stvz pcre-8.41]# ./configuer && make && make install
[root@izwz9e9bjg74ljcpzr7stvz openssl-fips-2.0.16]# ./config && make && make install
[root@izwz9e9bjg74ljcpzr7stvz nginx-1.13.7]# ./configure --with-pcre=../pcre-8.41/ --with-zlib=../zlib-1.2.11/ --with-openssl=../openssl-fips-2.0.16/
[root@izwz9e9bjg74ljcpzr7stvz nginx-1.13.7]# make && make install

安裝 C++ 編譯環境 (上面安裝過程當中如如有報錯,能夠看看是否是由於沒有安裝這個,可提早安裝)

yum install gcc-c++

運行Nginx

安裝好的Nginx路徑在 /usr/local/nginx

[root@izwz9e9bjg74ljcpzr7stvz ~]# cd /usr/local/nginx
[root@izwz9e9bjg74ljcpzr7stvz nginx]# ls
client_body_temp  conf  fastcgi_temp  html  logs  nginx.conf  proxy_temp  sbin  scgi_temp  uwsgi_temp

配置文件路徑:

/usr/local/nginx/conf/nginx.conf

運行Nginx:

[root@izwz9e9bjg74ljcpzr7stvz ~]# cd /usr/local/nginx/sbin
[root@izwz9e9bjg74ljcpzr7stvz sbin]# ./nginx
// 查看是否運行成功
[root@izwz9e9bjg74ljcpzr7stvz sbin]# netstat -ntlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      3525/nginx: master

瀏覽器輸入 IP 地址或域名便可見到歡迎頁面。

使用server命令啓動nginx服務

如今nginx啓動、關閉比較麻煩,關閉要找到PID號,而後殺死進程,啓動要進入到 /usr/local/nginx/sbin 目錄下使用命令,爲此咱們經過設置System V腳原本使用server命令啓動、關閉、重啓nginx服務。

  1. 在 /etc/init.d 目錄下建立nginx啓動腳本文件

    [root@izwz9e9bjg74ljcpzr7stvz ~]# cd /etc/init.d
    [root@izwz9e9bjg74ljcpzr7stvz init.d]# vim nginx
  2. 將如下代碼複製粘貼進去,而後保存。 注意 NGINX_BIN、CONFIGFILE、PIDFILE 三個目錄要對應好,默認是對應好的。在網上找了好多相關腳本代碼,都有不少問題,好像是和 CentOS 版本有關,下面腳本我在 CentOS 7 下使用正常。

    #! /bin/sh
    # chkconfig: 2345 55 25
    # Description: Startup script for nginx webserver on Debian. Place in /etc/init.d and
    # run 'update-rc.d -f nginx defaults', or use the appropriate command on your
    # distro. For CentOS/Redhat run: 'chkconfig --add nginx'
    
    ### BEGIN INIT INFO
    # Provides:          nginx
    # Required-Start:    $all
    # Required-Stop:     $all
    # Default-Start:     2 3 4 5
    # Default-Stop:      0 1 6
    # Short-Description: starts the nginx web server
    # Description:       starts nginx using start-stop-daemon
    ### END INIT INFO
    
    # Author:   licess
    # website:  http://lnmp.org
    
    PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
    NAME=nginx
    NGINX_BIN=/usr/local/nginx/sbin/$NAME
    CONFIGFILE=/usr/local/nginx/conf/$NAME.conf
    PIDFILE=/usr/local/nginx/logs/$NAME.pid
    
    case "$1" in
        start)
            echo -n "Starting $NAME... "
    
            if netstat -tnpl | grep -q nginx;then
                echo "$NAME (pid `pidof $NAME`) already running."
                exit 1
            fi
    
            $NGINX_BIN -c $CONFIGFILE
    
            if [ "$?" != 0 ] ; then
                echo " failed"
                exit 1
            else
                echo " done"
            fi
            ;;
    
        stop)
            echo -n "Stoping $NAME... "
    
            if ! netstat -tnpl | grep -q nginx; then
                echo "$NAME is not running."
                exit 1
            fi
    
            $NGINX_BIN -s stop
    
            if [ "$?" != 0 ] ; then
                echo " failed. Use force-quit"
                exit 1
            else
                echo " done"
            fi
            ;;
    
        status)
            if netstat -tnpl | grep -q nginx; then
                PID=`pidof nginx`
                echo "$NAME (pid $PID) is running..."
            else
                echo "$NAME is stopped"
                exit 0
            fi
            ;;
    
        force-quit)
            echo -n "Terminating $NAME... "
    
            if ! netstat -tnpl | grep -q nginx; then
                echo "$NAME is not running."
                exit 1
            fi
    
            kill `pidof $NAME`
    
            if [ "$?" != 0 ] ; then
                echo " failed"
                exit 1
            else
                echo " done"
            fi
            ;;
    
        restart)
            $0 stop
            sleep 1
            $0 start
            ;;
    
        reload)
            echo -n "Reload service $NAME... "
    
            if netstat -tnpl | grep -q nginx; then
                $NGINX_BIN -s reload
                echo " done"
            else
                echo "$NAME is not running, can't reload."
                exit 1
            fi
            ;;
    
        configtest)
            echo -n "Test $NAME configure files... "
    
            $NGINX_BIN -t
            ;;
    
        *)
            echo "Usage: $0 {start|stop|force-quit|restart|reload|status|configtest}"
            exit 1
            ;;
    
    esac
  3. 修改腳本權限

    chmod a+x /etc/init.d/nginx
  4. 註冊成服務

    chkconfig --add nginx
  5. 設置開機啓動

    chkconfig nginx on

這樣就能夠在任意目錄經過service啓動、關閉nginx

[root@izwz9e9bjg74ljcpzr7stvz ~]# service nginx start
[root@izwz9e9bjg74ljcpzr7stvz ~]# service nginx stop
[root@izwz9e9bjg74ljcpzr7stvz ~]# service nginx restart

配置nginx.conf反向代理多個node項目

  1. 啓動多個node項目,分別監聽不一樣端口,如

    • 項目1,監聽端口3000,爲博客項目,域名訪問 www.cl8023.com 或 cl8023.com
    • 項目2,監聽端口8023,爲遊戲項目,域名訪問 game.cl8023.com
  2. 在阿里雲服務區控制檯開放端口3000和8023,(80端口是必須的,nginx監聽)
  3. 綁定二級域名 game.cl8023.com,添加域名解析

    • 記錄類型:A
    • 主機記錄:game
    • 解析線路:默認
    • 記錄紙:IP地址
    • TTL至:10分鐘(默認)
  4. 修改nginx配置
    進入目錄 /usr/local/nginx/conf 修改配置文件nginx.conf

    [root@izwz9e9bjg74ljcpzr7stvz ~]# cd /usr/local/nginx/conf
    [root@izwz9e9bjg74ljcpzr7stvz conf]# ls
    fastcgi.conf          fastcgi_params          koi-utf  mime.types          nginx.conf          scgi_params          uwsgi_params          win-utf
    fastcgi.conf.default  fastcgi_params.default  koi-win  mime.types.default  nginx.conf.default  scgi_params.default  uwsgi_params.default
    [root@izwz9e9bjg74ljcpzr7stvz conf]# vim nginx.conf
    // server 內容替換爲
        server {
            listen 80;
            server_name game.cl8023.com;
            location / {
                proxy_set_header   Host      $http_host;
                proxy_pass         http://127.0.0.1:8023;
                proxy_redirect     off;
                proxy_set_header   X-Real-IP       $remote_addr;
                proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            }
        }
    
        server {
            listen 80;
            server_name cl8023.com www.cl8023.com;
            # 解決刷新404的問題
            location /blog {
                try_files $uri $uri/ /index.html;
            }
            location / {
                proxy_set_header   Host      $http_host;
                proxy_pass         http://127.0.0.1:3000;
                proxy_redirect     off;
                proxy_set_header   X-Real-IP       $remote_addr;
                proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            }
        }

    若只配置一個server,game.cl8023.com、cl8023.com、www.cl8023.com 都將能夠訪問到這個端口。想要反響代理更多端口,可再增長server,也能夠將server單獨出來爲一個文件,如game-8023.conf,blog-3000.conf,而後在nginx.conf中引入文件地址便可

    http {
        ......
        include ./vhost/game-8023.conf; 
        include ./vhost/blog-3000.conf;
        ......
    }
  5. 重啓nginx

    [root@izwz9e9bjg74ljcpzr7stvz ~]# service nginx restart

無誤的話即可以使用不一樣的域名訪問不一樣的項目。

相關文章
相關標籤/搜索