Node.js 快速开始
代码示例:
https://github.com/TencentCloudBase/cloudbase-examples/tree/master/cloudbaserun/node
点击下方按钮一键部署:
#
第 1 步:编写基础应用创建名为 helloworld
的新目录,并转到此目录中:
mkdir helloworldcd helloworld
创建一个包含以下内容的 package.json
文件:
{ "name": "helloworld", "description": "Simple hello world sample in Node", "version": "1.0.0", "main": "index.js", "scripts": { "start": "node index.js" }, "author": "Tencent CloudBase", "license": "Apache-2.0", "dependencies": { "express": "^4.17.1" }}
在同一目录中,创建一个 index.js
文件,并将以下代码行复制到其中:
const express = require("express");const app = express();
app.get("/", (req, res) => { res.send(`Hello World!`);});
const port = 8080;app.listen(port, () => { console.log(`helloworld: listening on port ${port}`);});
此代码会创建一个基本的 Web 服务器,侦听 8080
端口。
#
第 2 步:将应用容器化在项目根目录下,创建一个名为 Dockerfile
的文件,内容如下:
# 使用官方 Node.js 12 轻量级镜像.# https://hub.docker.com/_/nodeFROM node:12-slim
# 定义工作目录WORKDIR /usr/src/app
# 将依赖定义文件拷贝到工作目录下COPY package*.json ./
# 以 production 形式安装依赖RUN npm install --only=production
# 将本地代码复制到工作目录内COPY . ./
# 启动服务CMD [ "node", "index.js" ]
添加一个 .dockerignore
文件,以从容器映像中排除文件:
Dockerfile.dockerignorenode_modulesnpm-debug.log
#
第 3 步(可选):本地构建镜像如果您本地已经安装了 Docker,可以运行以下命令,在本地构建 Docker 镜像:
docker build -t helloworld .
构建成功后,运行 docker images
,可以看到构建出的镜像:
REPOSITORY TAG IMAGE ID CREATED SIZEhelloworld latest 1c8dfb88c823 8 seconds ago 146MB
随后您可以将此镜像上传至您的镜像仓库。