用 Express generator 快速開始
- 安裝 Express application generator
$ npm install express-generator -g
- 用Express generator 創(chuàng)建 nodeweb 項(xiàng)目
$ express --ejs nodeweb
--ejs 表示用ejs做view engine,默認(rèn)使用jade - 安裝dependencies
cd nodeweb
npm install
- 運(yùn)行剛才創(chuàng)建的項(xiàng)目
- On MacOS or Linux
$ DEBUG=nodeweb:* npm start
- On Windows, use this command:
> set DEBUG=myapp:* & npm start
這里的DEBUG是node的 environment variable,在js文件中可以通過process.env.DEBUG
得到前面設(shè)置的DEBUG的值
Serving static files in Express
app.use('/static', express.static(path.join(__dirname, 'public')))
express.static 是 express 的一個(gè)內(nèi)置 middleware磕潮。
用 git 同步代碼
在服務(wù)器上弧可, ce ~/web
, 把網(wǎng)站代碼clone下來
用 PM2 運(yùn)行
安裝 pm2
npm install pm2@latest -g
啟動(dòng)網(wǎng)站
pm2 start apps.json
pm2 生成啟動(dòng)腳本
方式1
$ pm2 startup centos
[PM2] You have to run this command as root. Execute the following command:
sudo su -c "env PATH=$PATH:/usr/bin pm2 startup centos -u red --hp /home/red"
把sudo su...這句話拷貝捷泞,粘貼再次運(yùn)行秉氧,在/etc/init.d/下生成一個(gè) pm2-init.sh, 每次系統(tǒng)啟動(dòng)會(huì)自動(dòng)運(yùn)行址儒。
方式2
方式1產(chǎn)生的腳本在init.d目錄僻焚, centos 7 已經(jīng)是用 systemd 了允悦,所以下面的方式更好 $ pm2 startup systemd
[PM2] You have to run this command as root. Execute the following command:
sudo su -c "env PATH=$PATH:/usr/bin pm2 startup systemd -u red --hp /home/red"
再次運(yùn)行sudo su -c "env PATH=$PATH:/usr/bin pm2 startup systemd -u red --hp /home/red"
這次會(huì)在 /etc/systemd/system
下面產(chǎn)生pm2.service
.
安裝 Nginx
現(xiàn)在curl localhost:3000
,網(wǎng)站能運(yùn)行虑啤,但是3000 端口被 firewalld 封鎖隙弛,從服務(wù)器外部還是不能打開網(wǎng)站。這時(shí)可以給 firewalld 增加一個(gè) service 打開 3000 端口狞山,也可以安裝 nginx 做反向代理驶鹉。
安裝 nginx
sudo yum install nginx
先刪除 nginx 默認(rèn)配置里的 server 部分,打開 /etc/nginx/nginx.conf
, 刪除 server {... ...}里面的內(nèi)容铣墨,保存室埋。
添加modular 配置,在/etc/nginx/nginx.conf
里的 http 部分找到 include /etc/nginx/conf.d/*.conf
, 這句話好像默認(rèn)就存在姚淆。
添加my-web的配置孕蝉,在 /etc/nginx/conf.d/下新建文件 my-web.conf, 添加內(nèi)容
server {
listen 80;
server_name yy.xx.com;
location / {
proxy_pass http://127.0.0.1:3000/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#client_max_body_size 100m;
}
}
檢查配置文件的語法是否有錯(cuò): sudo nginx -t
重啟動(dòng) nginx, sudo systemctl restart nginx
這時(shí)候腌逢,本地機(jī)器 http://yy.xx.com應(yīng)該可以打開 my-web降淮。