在CentOS上部署Node.js項目通常涉及以下幾個步驟:
更新系統:
sudo yum update -y
安裝Node.js: 你可以使用NodeSource倉庫來安裝最新版本的Node.js。
curl -sL https://rpm.nodesource.com/setup_14.x | sudo bash -
sudo yum install -y nodejs
安裝NVM(Node Version Manager)(可選但推薦): NVM可以幫助你管理不同版本的Node.js。
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
source ~/.bashrc
安裝項目依賴: 進入你的項目目錄,初始化npm并安裝所需的依賴包。
cd /path/to/your/project
npm init -y
npm install
配置Nginx反向代理(可選): 如果你希望使用Nginx作為反向代理來處理HTTP請求,可以安裝并配置Nginx。
sudo yum install -y nginx
sudo systemctl start nginx
sudo systemctl enable nginx
編輯Nginx配置文件(通常位于/etc/nginx/conf.d/
目錄下),添加一個新的服務器塊來處理你的Node.js應用。
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass http_upgrade;
}
}
重啟Nginx以應用更改。
sudo systemctl restart nginx
啟動Node.js應用: 使用PM2等進程管理工具來啟動你的Node.js應用,確保應用在后臺運行并在服務器重啟后自動啟動。
npm install -g pm2
pm2 start app.js
配置安全組: 確保在ECS實例的安全組中添加相應的入站規則,以允許外部訪問你的應用所使用的端口(例如3000端口)。
以上步驟是在CentOS上部署Node.js項目的基本流程。根據你的具體需求,可能還需要進行其他配置,比如數據庫的連接、環境變量的設置等。