Node.js Quick Start
This document introduces 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 the Basic Application
Create a new directory named helloworld
and navigate into it:
mkdir helloworld
cd helloworld
Create a package.json
file containing the following:
{
"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 lines of code 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 retrieve remote data (here using ipinfo.io as an example)
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 creates a basic Web server that listens on port 80
.
Step 2: Containerize the Application
In the project root directory, create a file named Dockerfile
with the following content:
# Use the official Node.js lightweight image
# https://hub.docker.com/_/node
FROM node:22-alpine
# Set timezone
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 file 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 local code to the working directory
COPY . .
# Expose port
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): Build and Run Locally
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
Then you can 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 Run
If you have already installed the 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 Specification
- Configuration is typically placed in the project directory or configured using environment variables.
- During service deployment, simply specify the service's startup port on Cloud Hosting.
- It is recommended to use environment variables to manage configurations across different environments.
Best Practices
- Only install production dependencies to reduce the image size
- Use a domestic mirror source to speed up dependency installation
- Set the container time zone appropriately
- Use .dockerignore to exclude unnecessary files
Node.js framework project samples can refer to: