在CentOS上配置Node.js可以分为几个步骤,包括安装Node.js、配置环境变量、使用npm管理模块以及设置反向代理等。以下是详细的步骤:
更新系统包:
sudo yum update -y
安装EPEL(Extra Packages for Enterprise Linux)仓库:
sudo yum install epel-release
使用NodeSource安装Node.js:
curl -sL https://rpm.nodesource.com/setup_14.x | sudo bash -
安装Node.js和npm:
sudo yum install -y nodejs
验证安装:
node -v
npm -v
使用.env文件和dotenv库:
npm install dotenv
PORT=3000
DATABASE_URL=mysql://user:password@localhost/db
require('dotenv').config();
const port = process.env.PORT || 3000;
console.log(`Server is running on port ${port}`);
命令行配置环境变量: 在启动Node.js应用时,可以通过命令行传递环境变量:
NODE_ENV=production PORT=3000 node app.js
安装模块:
sudo npm install express --save
全局安装模块:
sudo npm install -g nodemon
安装Nginx:
sudo yum install nginx
配置Nginx:
编辑Nginx配置文件 /etc/nginx/nginx.conf
,在http块中添加以下配置:
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
重启Nginx:
sudo systemctl restart nginx
sudo systemctl enable nginx
通过以上步骤,你可以在CentOS上成功配置Node.js环境,并运行你的Node.js应用程序。