跳到主要内容

Node.js 快速开始

本文档介绍从零开始手动将一个 Node.js 应用容器化,并部署到 CloudBase 云托管服务。

代码示例:

https://github.com/TencentCloudBase/cloudbase-examples/tree/master/cloudbaserun/node

第 1 步:编写基础应用

创建名为 helloworld 的新目录,并转到此目录中:

mkdir helloworld
cd helloworld

创建一个包含以下内容的 package.json 文件:

{
"name": "helloworld",
"description": "Simple hello world sample in Node",
"version": "1.0.0",
"type": "module",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"author": "Tencent CloudBase",
"license": "Apache-2.0"
}

在同一目录中,创建一个 index.js 文件,并将以下代码行复制到其中:

import { createServer } from "node:http";
import { Readable } from "node:stream";

const server = createServer(async (req, res) => {
if (req.url === "/") {
res.writeHead(200);
res.end("Hello World!");
} else if (req.url === "/myip") {
// 设置 CORS 头,允许跨域请求
res.setHeader("Access-Control-Allow-Origin", "*");

try {
// 使用 fetch 获取远程数据(这里使用 ipinfo.io 作为示例)
const response = await fetch("https://ipinfo.io", {
headers: {
Accept: "application/json",
},
});
Readable.fromWeb(response.body).pipe(res);
} catch (error) {
console.error(error);
res.writeHead(500);
res.end(JSON.stringify({ error: "Failed to fetch remote data" }));
}
} else {
res.writeHead(404);
res.end(JSON.stringify({ error: "Not Found" }));
}
});

const port = 80;
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
console.log(
`Try accessing http://localhost:${port}/myip to see your IP info`
);
});

此代码会创建一个基本的 Web 服务器,侦听 80 端口。

第 2 步:将应用容器化

在项目根目录下,创建一个名为 Dockerfile 的文件,内容如下:

# 使用官方 Node.js 轻量级镜像.
# https://hub.docker.com/_/node
FROM node:22-alpine

# 设置时区
RUN apk add tzdata && \
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
echo Asia/Shanghai > /etc/timezone && \
apk del tzdata

# 定义工作目录
WORKDIR /app

# 将依赖定义文件拷贝到工作目录下
COPY package*.json ./

# 使用国内镜像源安装依赖
# RUN npm config set registry https://mirrors.cloud.tencent.com/npm/ && \
# npm install --only=production && \
# npm cache clean --force

# 将本地代码复制到工作目录内
COPY . .

# 暴露端口
EXPOSE 80

# 启动服务
CMD [ "node", "index.js" ]

添加一个 .dockerignore 文件,以从容器映像中排除文件:

Dockerfile
.dockerignore
node_modules
npm-debug.log

第 3 步(可选):本地构建和运行

如果您本地已经安装了 Docker,可以运行以下命令,在本地构建 Docker 镜像:

docker build -t helloworld-nodejs .

构建成功后,运行 docker images,可以看到构建出的镜像:

REPOSITORY     TAG       IMAGE ID         CREATED          SIZE
helloworld-nodejs latest 1c8dfb88c823 8 seconds ago 163MB

随后您可以将此镜像上传至您的镜像仓库。

docker run  -p 80:80  helloworld-nodejs

访问 http://localhost,您应该能看到 "Hello World!" 的输出,访问 http://localhost/myip,您应该能看到您的 IP 信息。

第 4 步:部署到 CloudBase 云托管

如果您已经安装了 CloudBase CLI,可以在项目目录下使用以下命令将应用部署到 CloudBase 云托管:

tcb cloudrun deploy

输入环境和服务名称后,CLI 会自动打包应用像并部署到云托管。更多部署方式请参考 部署服务

配置规范

  • 配置一般放到项目目录中,或者使用环境变量配置
  • 服务部署时,在云托管上指定服务的启动端口即可
  • 建议使用环境变量来管理不同环境的配置

最佳实践

  1. 只安装生产环境依赖以减小镜像体积
  2. 使用国内镜像源加速依赖安装
  3. 合理设置容器时区
  4. 使用 .dockerignore 排除不必要的文件

Nodejs 框架项目示例可以参考: