Thiết lập hạ tầng Express.js vững chãi: Giải pháp quản lý quy trình với PM2 trên Ubuntu.
Sau khi cài đặt NVM (Node Version Manager/NeVerMind), chúng ta có thể dễ dàng cài đặt các phiên bản Node.js khác nhau và chọn phiên bản cần sử dụng cho ứng dụng của mình.
Cài đặt NVM trên Ubuntu
Tải và cài đặt
Kiểm tra phiên bản nvm
nvm --versionCài đặt Nodejs phiên bản 12
nvm install 18.17.0# check if installed
nvm --version==> 0.39.5
# list available Node.js versions
nvm ls-remote# choose one version and install it
# example of v10.4.1 installation
node --version==> v12.16.2
Khai báo dùng phiên bản nodejs cho nvm
nvm use 12.16.22nvm alias default 18.17.0# check more nvm usage
nvm --helpPM2 Cài đặt Process Manager 2
npm install pm2@latest -g ;# check if installed properly
pm2 -V# start our server with PM2 after instal Express js
pm2 start server.js2pm2 startup# this will generate another command that you need to run
# We also need to save what processes
# should get started with pm2
pm2 save#To restart an application:
pm2 restart 02pm2 restart all#To stop a specified application:
pm2 stop api
pm2 stop
#To stop and delete an application:
pm2 delete api
pm2 delete all
#To list all running applications:
pm2 list
# Or
pm2
#To reset the restart counter:
pm2 reset all
Cài Express Js
# go to your user's directory
cd /home/lukas
# create folder simpleServer
mkdir simpleServer
# go inside
cd simpleServer
# create package.json
npm init -y
# install Express.js
npm install express
# open nano
nano server.js
# to save, press Ctrl + X ==> Y ==> Enter
--------------------------
const express = require('express');2const app = express();3app.get('/', (req, res) => {4 res.send("Hello World!");5});6const port = 3000;7const server = app.listen(port, () => {8 console.log(`Listening on http://localhost:${port}`);9});--------------------------
Cài Nginx web server proxy
sudo apt-get install nginx
cd /etc/nginx/sites-available
sudo nano simpleServer
--------------------------
server {
listen 80;
server_name www.example.com example.com;
location / {
proxy_pass http://localhost:3000/;
}
}
--------------------------
# check if your configuration is ok
sudo nginx -t
# enable your configuration
sudo ln -s /etc/nginx/sites-available/simpleServer /etc/nginx/sites-enabled
# restart nginx
sudo service restart nginx
Nguồn: