Node.js: Getting started
Learn how to deploy a Node.js service on Stackhero quickly and securely
👋 Welcome to the Stackhero documentation!
Stackhero offers a ready-to-use Node.js cloud solution that provides a host of benefits, including:
- Deploy your application in seconds with a simple
git push.- Use your own domain name and benefit from the automatic configuration of HTTPS certificates for enhanced security.
- Enjoy peace of mind with automatic backups, one-click updates, and straightforward, transparent, and predictable pricing.
- Get optimal performance and robust security thanks to a private and dedicated VM.
Save time and simplify your life: it only takes 5 minutes to try Stackhero's Node.js cloud hosting solution!
Deploying your Node.js service on Stackhero is designed to be quick, efficient, and reliable. In this guide, we will walk through the essential steps to get your app up and running in just a few minutes, while keeping security and performance in mind.
Start a Node.js service
To begin, let us create a Node.js service on Stackhero. This will form the foundation for your application deployment and give you access to all the benefits of Stackhero's cloud hosting.
Prerequisites
Before you get started, make sure you have the following tools ready:
- Git: You can download it from https://git-scm.com/downloads.
- Windows users: For a smoother experience, it is a good idea to use Windows Terminal, available from the Microsoft Store.
Configure your service
The main configuration step is to update your SSH public key. This key allows Stackhero to securely access your code repository.
To find your public key, you can run one of these commands in your terminal:
cat ~/.ssh/id_rsa.pub
or
cat ~/.ssh/id_ed25519.pub
If you do not have an SSH key pair yet, you can generate one by running ssh-keygen on Linux or macOS, or ssh-keygen.exe on Windows.
Once you have your public key, log in to the Stackhero dashboard, select your Node.js service, go to its configuration section, and paste your key in the provided field.
Tip: If you would like your SSH public key to be available for all future services, you can set it globally. Just head to the Stackhero dashboard, click your profile picture (top right), go to "Your profile", and paste your SSH public key there.
Clone the example
To help you get started, we provide an example Node.js application that shows how deployment works on Stackhero. You can clone the repository with these commands:
git clone https://github.com/stackhero-io/nodejsGettingStarted.git stackhero-nodejs-getting-started
cd stackhero-nodejs-getting-started
Configure the remote repository server
Deploying your application via Git on Stackhero is straightforward. On your service's main page, you will find a command to add a Git remote, which might look something like this:
git remote add stackhero ssh://stackhero@<XXXXXX>.stackhero-network.com:222/project.git
You can copy and paste this command into your terminal to set up the remote.
Deploy your Node.js application
To deploy, simply push your code to Stackhero with:
git push stackhero main
The first time you push, you will be prompted to confirm the key fingerprint. Just type "yes" to continue.
In a few moments, your application should be live. You can verify its status by visiting the website URL shown on your Stackhero dashboard (for example, https://<XXXXXX>.stackhero-network.com).
That is it, your application is now deployed.
If you need to make changes, just update your app.js file, commit, and push your modifications:
git add -A .
git commit -m "Update app.js"
git push stackhero main
Deploy an existing application
If you already have a Node.js application, you can add the Stackhero remote as described above and deploy your code with:
git push stackhero main
Handle error "failed to push some refs to '[...]'"
If you encounter this error:
error: failed to push some refs to '[...]'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
(e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
It means your local repository is out of sync with the remote. You can force the push with:
git push -f stackhero main
Handle error "src refspec main does not match any"
If you see the following when pushing:
error: src refspec main does not match any
error: failed to push some refs to 'ssh://<XXXXXX>.stackhero-network.com:222/project.git'
This usually means the main branch does not exist. You might try pushing the master branch instead:
git push stackhero master
Handle error "Everything up-to-date" when pushing
If Git tells you "Everything up-to-date" but your changes are not deployed, it could be because you forgot to commit. Try running:
git add -A .
git commit -m "Your commit message"
git push stackhero main
If you have not made any changes but still want to trigger a deployment, you can force an empty commit:
git commit --allow-empty -m "Force update"
git push stackhero main
Deploy a branch other than main
If you would like to deploy a branch other than main, like production, you can do so with:
git push stackhero production:main
Deploy a tag
If you use tags and want to deploy a specific tag (for example, v1.0), you can run:
git push stackhero 'v1.0^{}:main'
The ^{} ensures the commit associated with the tag is pushed.
Roll back or deploy a specific commit
If you need to deploy a specific commit, first find the commit hash using git log. Then deploy it with:
git push -f stackhero <HASH>:main
Deploy to multiple environments
You might want separate environments for production and staging. To rename the current remote from stackhero to stackhero-staging, you can run:
git remote rename stackhero stackhero-staging
Next, create a new Node.js service in your Stackhero dashboard and add it as stackhero-production:
git remote add stackhero-production ssh://stackhero@<XXXXXX>.stackhero-network.com:222/project.git
You can then deploy to each environment with:
git push stackhero-production main
or
git push stackhero-staging main
Save your SSH private key password in macOS keychain
On macOS, you might be asked for your SSH key password every time you push code. For convenience and security, you can save it in the macOS keychain by running:
/usr/bin/ssh-add --apple-use-keychain ~/.ssh/id_rsa
This command saves your key password so you will not be prompted again during future deployments.
Handle secrets
When working with staging and production environments, it is important to handle secrets like tokens or passwords securely. Rather than storing secrets in your repository, you can use environment variables for extra safety.
You can add environment variables in the Stackhero dashboard and access them in your Node.js code. For example, if you define a variable named mySecret, you can access it in your app like this:
process.env.mySecret
Open other network ports
If your application needs to use protocols other than HTTP, you may want to open additional TCP or UDP ports. You can do this directly in the Stackhero dashboard by specifying the public entry port, the destination port on your Node.js service, and the protocol (TCP or UDP).
Store files
For storing user files, such as photos, it is best to use an object storage solution. This helps you share files across multiple services and instances, and keeps your code separate from your data. We recommend MinIO as a fast, easy, and powerful solution that is compatible with the Amazon S3 protocol.
If you prefer local storage, you can use the persistent storage available with your Node.js instance. This storage is located at /persistent/storage/.
CAUTION: Always store data inside the
/persistent/storage/folder.Data stored outside this folder may be lost if your instance reboots or if you push code changes.
Graceful shutdown
When you deploy a new version of your app, the previous version is given a termination signal before it shuts down. This gives your app time to close database connections and stop other services gracefully.
The termination signal SIGTERM is sent to your app. You can handle this signal in your code like this:
process.on('SIGTERM', () => {
// This log appears on the Stackhero dashboard in the "logs" tab
console.info('SIGTERM signal received.');
// Close open database connections or other services here
// ...
});
Run your code on multiple CPU cores
By default, Node.js uses a single core and one thread. To take advantage of all available CPU cores, you might want to use the Node.js cluster API. You can find the official documentation here: https://nodejs.org/api/cluster.html.
Here is a simple example that creates an HTTP server using all available CPUs:
const cluster = require('cluster');
const http = require('http');
const cpusCount = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers
for (let i = 0; i < cpusCount; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died`);
});
} else {
// Workers share any TCP connection, in this case, an HTTP server
http.createServer((req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
console.log(`Worker ${process.pid} started`);
}