centos

Node.js在CentOS上怎么配置

小樊
90
2025-02-12 22:38:42
栏目: 编程语言

在CentOS上配置Node.js可以分为几个步骤,包括安装Node.js、配置环境变量、使用npm管理模块以及设置反向代理等。以下是详细的步骤:

安装Node.js

  1. 更新系统包

    sudo yum update -y
    
  2. 安装EPEL(Extra Packages for Enterprise Linux)仓库

    sudo yum install epel-release
    
  3. 使用NodeSource安装Node.js

    curl -sL https://rpm.nodesource.com/setup_14.x | sudo bash -
    
  4. 安装Node.js和npm

    sudo yum install -y nodejs
    
  5. 验证安装

    node -v
    npm -v
    

配置环境变量

  1. 使用.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}`);
      
  2. 命令行配置环境变量: 在启动Node.js应用时,可以通过命令行传递环境变量:

    NODE_ENV=production PORT=3000 node app.js
    

使用npm管理模块

  1. 安装模块

    sudo npm install express --save
    
  2. 全局安装模块

    sudo npm install -g nodemon
    

设置反向代理(如使用Nginx)

  1. 安装Nginx

    sudo yum install nginx
    
  2. 配置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;
        }
    }
    
  3. 重启Nginx

    sudo systemctl restart nginx
    sudo systemctl enable nginx
    

通过以上步骤,你可以在CentOS上成功配置Node.js环境,并运行你的Node.js应用程序。

0
看了该问题的人还看了