Running a Node.js
application in a production environment requires careful configuration and optimization for performance and security. In this guide, we’ll walk through the steps to set up a Node.js
application for production on Ubuntu 22.04
using the Caddy
web server.
Table of Contents
- 1. Introduction
- 2. Prerequisites
- 3. Install Node.js and npm
- 4. Set Up a Node.js Application
- 5. Install Caddy
- 6. Configure Caddy for Reverse Proxy
- 7. Set Up Process Manager - PM2
- 9. Conclusion
1. Introduction
Setting up a Node.js application for production involves several key steps, including installing Node.js, configuring a reverse proxy with Caddy, using a process manager like PM2, securing the application with HTTPS, and optimizing for performance.
2. Prerequisites
Before you begin, ensure that you have:
- An Ubuntu 22.04 server with a sudo-enabled user.
- A Node.js application ready for deployment.
- Caddy installed on the server.
3. Install Node.js and npm
Install Node.js and npm using the NodeSource repository:
sudo apt update
sudo apt install -y nodejs npm
4. Set Up a Node.js Application
Upload your Node.js application to the server or clone it from a version control system.
Install application dependencies:
cd /path/to/your/app
npm install --production
5. Install Caddy
Download and install Caddy using the official instructions: Caddy Installation
Ensure that Caddy is running:
caddy run
6. Configure Caddy for Reverse Proxy
Create a Caddyfile
in the same directory as your Node.js
application:
your-domain.com {
reverse_proxy localhost:your-node-app-port
}
Replace your-domain.com
with your actual domain and your-node-app-port
with the port your Node.js application is running on.
7. Set Up Process Manager - PM2
Install PM2 globally to manage your Node.js application as a background process:
sudo npm install -g pm2
Start your Node.js application with PM2:
pm2 start your-app.js
To ensure PM2 starts on system boot:
pm2 startup systemd
pm2 save
- Configure Firewall Set up the Uncomplicated Firewall (UFW) and allow necessary ports:
sudo apt install ufw
sudo ufw allow OpenSSH
sudo ufw allow 80
sudo ufw allow 443
sudo ufw enable
9. Conclusion
You’ve successfully set up your Node.js application for production on Ubuntu 22.04 using Caddy. This guide covers essential steps from installing dependencies to optimizing performance and securing your application. Regularly update packages and monitor your server for continuous improvement. Happy deploying!