Introduction
Deploying a Node.js application involves setting up a server, configuring dependencies, and ensuring security and performance. This chapter covers deployment strategies for both self-hosted and cloud-based solutions.
1. Choosing a Deployment Method
- Self-hosted (VPS/ Dedicated Server): DigitalOcean, Linode, Scaleway
- Cloud Platforms: AWS, Google Cloud, Azure
- Platform as a Service (PaaS): Heroku, Vercel, Railway
- Containerization: Docker, Kubernetes
2. Preparing the Application for Deployment
- Use environment variables for secrets (
dotenv
) - Minimize package dependencies
- Remove
devDependencies
in production - Use process managers (PM2) for stability
Example .env
file:
PORT=3000
DB_URL=mongodb://localhost:27017/myapp
JWT_SECRET=supersecretkey
Load .env
variables in the application:
require("dotenv").config();
const port = process.env.PORT || 3000;
3. Deploying on a VPS (DigitalOcean, Linode, Scaleway)
- Set up a server (Ubuntu/Debian-based recommended)
- Install Node.js and
npm
:curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - sudo apt install -y nodejs
- Clone the repository:
git clone https://github.com/your-repo.git cd your-repo
- Install dependencies:
npm install --production
- Run the application using PM2:
npm install -g pm2 pm2 start server.js --name myapp pm2 save && pm2 startup
- Set up a reverse proxy with Nginx (optional but recommended for security and SSL support).
4. Deploying on Cloud Platforms (AWS, GCP, Azure)
-
AWS EC2 / GCP Compute Engine / Azure VM
- Follow the VPS steps above.
-
AWS Elastic Beanstalk
- Install the CLI:
npm install -g aws-eb-cli
- Initialize and deploy:
eb init eb create my-node-app
- Install the CLI:
-
Google Cloud App Engine
- Create an
app.yaml
:runtime: nodejs18 env: standard
- Deploy:
gcloud app deploy
- Create an
5. Deploying on PaaS (Heroku, Vercel, Railway)
-
Heroku
heroku create myapp git push heroku main
-
Vercel (for frontend + APIs)
vercel
-
Railway
railway init railway up
6. Containerizing with Docker
-
Create a
Dockerfile
FROM node:18 WORKDIR /app COPY package.json . RUN npm install --production COPY . . CMD ["node", "server.js"] EXPOSE 3000
-
Build and run the Docker container
docker build -t myapp . docker run -d -p 3000:3000 myapp
-
Push to Docker Hub (optional)
docker login docker tag myapp yourusername/myapp docker push yourusername/myapp
Exercises
- Deploy a simple Node.js API on a VPS (DigitalOcean, Linode, or Scaleway).
- Deploy a Node.js application on Heroku and test its availability.
- Use Docker to containerize a Node.js API and run it locally.
- Set up a reverse proxy for your Node.js application using Nginx.
- Implement a CI/CD pipeline for automated deployments using GitHub Actions or GitLab CI.
Conclusion
This chapter covered deploying Node.js applications on VPS, cloud platforms, PaaS, and Docker. Next, we will explore scaling and monitoring Node.js applications.