0
0
NodejsHow-ToBeginner · 4 min read

How to Deploy Node.js to AWS: Step-by-Step Guide

To deploy a Node.js app to AWS, use AWS Elastic Beanstalk which automates server setup. Package your app with a package.json, then run eb init and eb create commands to launch it on AWS.
📐

Syntax

Deploying Node.js to AWS Elastic Beanstalk involves these main commands:

  • eb init: Initializes your project with AWS Elastic Beanstalk.
  • eb create: Creates an environment and deploys your app.
  • eb deploy: Deploys updates to your existing environment.

You also need a package.json file to define your app and dependencies.

bash
npm init -y
npm install express

# Initialize Elastic Beanstalk
eb init

# Create environment and deploy
eb create my-node-env

# Deploy updates
eb deploy
💻

Example

This example shows a simple Node.js app deployed to AWS Elastic Beanstalk. It uses Express to serve a basic web page.

javascript
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;

app.get('/', (req, res) => {
  res.send('Hello from AWS Elastic Beanstalk!');
});

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});
Output
Server running on port 3000
⚠️

Common Pitfalls

Common mistakes when deploying Node.js to AWS include:

  • Not setting the PORT environment variable; AWS Elastic Beanstalk assigns it dynamically.
  • Missing package.json or not specifying the start script.
  • Not committing all files before deploying.
  • Using outdated AWS CLI or Elastic Beanstalk CLI versions.

Always test your app locally with npm start before deploying.

javascript
/* Wrong: hardcoded port */
const port = 3000;

/* Right: use environment port */
const port = process.env.PORT || 3000;
📊

Quick Reference

Steps to deploy Node.js app to AWS Elastic Beanstalk:

  1. Install AWS CLI and EB CLI.
  2. Initialize your project with eb init.
  3. Create environment with eb create.
  4. Deploy updates with eb deploy.
  5. Access your app URL provided by Elastic Beanstalk.

Key Takeaways

Use AWS Elastic Beanstalk CLI commands eb init, eb create, and eb deploy to deploy Node.js apps easily.
Always use process.env.PORT in your Node.js app to work with AWS assigned ports.
Make sure your package.json includes a start script to launch your app.
Test your app locally before deploying to avoid common errors.
Keep AWS CLI and EB CLI tools updated for smooth deployment.