阅读量:4
在CentOS上配置Node.js可以分为几个步骤,包括安装Node.js、配置环境变量、使用npm管理模块以及设置反向代理等。以下是详细的步骤:
安装Node.js
-
更新系统包:
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库:
- 安装dotenv库:
npm install dotenv - 在项目根目录下创建一个.env文件,并添加环境变量:
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}`);
- 安装dotenv库:
-
命令行配置环境变量: 在启动Node.js应用时,可以通过命令行传递环境变量:
NODE_ENV=production PORT=3000 node app.js
使用npm管理模块
-
安装模块:
sudo npm install express --save -
全局安装模块:
sudo npm install -g nodemon
设置反向代理(如使用Nginx)
-
安装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应用程序。
以上就是关于“Node.js在CentOS上怎么配置”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm