Skip to main content

Node.js Quick Start Guide

This document describes how to manually containerize a Node.js application from scratch and deploy it to the CloudBase cloud hosting service.

Sample code:

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

or deploy to cloud hosting with one click:

Step 1: Write a Basic Application

Create a new directory named helloworld and change to this directory:

mkdir helloworld
cd helloworld

Create a package.json file containing the following content:

{
"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"
}

In the same directory, create an index.js file and copy the following code lines into it:

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") {
// Set CORS headers to allow cross-origin requests
res.setHeader("Access-Control-Allow-Origin", "*");

try {
// Use fetch to get remote data (using ipinfo.io as an example here)
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`
);
});

This code will create a basic Web server listening on port 80.

Step 2: Containerize the Application

Create a file named Dockerfile in the project root directory with the following content:

# Use the official Node.js lightweight image.
# https://hub.docker.com/_/node
FROM node:22-alpine

# Set the time zone
RUN apk add tzdata && \
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
echo Asia/Shanghai > /etc/timezone && \
apk del tzdata

# Define the working directory
WORKDIR /app

# Copy the dependency definition files to the working directory
COPY package*.json ./

# Use a domestic mirror source to install dependencies
# RUN npm config set registry https://mirrors.cloud.tencent.com/npm/ && \
# npm install --only=production && \
# npm cache clean --force

# Copy the local code to the working directory
COPY . .

# Install composer
EXPOSE 80

# Start the service.
CMD [ "node", "index.js" ]

Add a .dockerignore file to exclude files from the container image:

Dockerfile
.dockerignore
node_modules
npm-debug.log

Step 3 (Optional): Local Build and Run

If you have Docker installed locally, you can run the following command to build the Docker image locally:

docker build -t helloworld-nodejs .

After a successful build, run docker images to view the built image:

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

You can then upload this image to your image repository.

docker run  -p 80:80  helloworld-nodejs

Access http://localhost, you should see the "Hello World!" output. Access http://localhost/myip, you should see your IP information.

Step 4: Deploy to CloudBase Cloud Hosting

If you have installed CloudBase CLI, you can use the following command in the project directory to deploy the application to CloudBase Cloud Hosting:

tcb cloudrun deploy

After entering the environment and service names, the CLI will automatically package the application image and deploy it to Cloud Hosting. For more deployment methods, refer to Deploying Services.

Configuration Specifications

  • Configuration is typically placed in the project directory or configured using environment variables
  • During service deployment, specify the startup port for the service on cloud hosting.
  • It is recommended to use environment variables to manage configurations across different environments

Best Practices

  1. Only install production dependencies to reduce image size
  2. Use a domestic mirror source to accelerate dependency installation
  3. Properly set the container time zone
  4. Use .dockerignore to exclude unnecessary files

You can refer to the following Nodejs framework project examples: