温馨提示×

如何在 Ubuntu 上搭建 Nodejs 服务器

小樊
43
2025-02-25 11:09:47
栏目: 云计算
亿速云爆款云服务器,独享5M带宽,BGP线路,安全稳定,0.96元/天! 查看详情>>

在 Ubuntu 上搭建 Node.js 服务器相对简单。以下是一个详细的步骤指南:

1. 更新系统包

首先,确保你的系统包是最新的:

sudo apt update
sudo apt upgrade -y

2. 安装 Node.js

你可以使用 NodeSource 提供的安装脚本来安装最新版本的 Node.js。以下是安装 Node.js 14.x 版本的示例:

安装 NodeSource 仓库

curl -fsSL https://deb.nodesource.com/setup_14.x | sudo -E bash -

安装 Node.js 和 npm

sudo apt install -y nodejs

验证安装

安装完成后,你可以通过以下命令验证 Node.js 和 npm 是否安装成功:

node -v
npm -v

3. 创建项目目录

创建一个新的目录来存放你的 Node.js 项目:

mkdir my-node-server
cd my-node-server

4. 初始化 Node.js 项目

使用 npm 初始化一个新的 Node.js 项目:

npm init -y

这会创建一个 package.json 文件,其中包含项目的基本信息。

5. 安装 Express

Express 是一个流行的 Node.js Web 框架,可以帮助你快速搭建服务器。安装 Express:

npm install express

6. 创建服务器文件

在项目目录中创建一个名为 server.js 的文件,并添加以下代码:

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

7. 启动服务器

在终端中运行以下命令来启动服务器:

node server.js

你应该会看到类似以下的输出:

Server is running on http://localhost:3000

8. 访问服务器

打开浏览器,访问 http://localhost:3000,你应该会看到 “Hello World!” 的消息。

9. 设置生产环境

在生产环境中,你可能需要使用进程管理器(如 PM2)来管理你的 Node.js 应用程序。安装 PM2:

npm install pm2 -g

然后使用 PM2 启动你的服务器:

pm2 start server.js

PM2 提供了许多有用的功能,如日志管理、自动重启等。

10. 配置防火墙

如果你需要从外部访问你的服务器,确保你的防火墙允许 HTTP(端口 80)和 HTTPS(端口 443)流量。你可以使用 ufw 来配置防火墙:

sudo ufw allow 80
sudo ufw allow 443
sudo ufw enable

现在,你的 Node.js 服务器已经在 Ubuntu 上搭建完成,并且可以运行了。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:如何在Linux上搭建Node.js服务器

0