AWS Builder Center

Deploying a Node.js Application on AWS EC2 Using Docker: A Complete Step-by-Step Guide

Learn how to deploy and manage a Node.js application on AWS EC2 using Docker. This beginner-friendly tutorial covers EC2 setup, Docker installation, containerization, deployment, updates, troubleshooting, and essential DevOps best practices.

Deploying a Node.js Application on AWS EC2 Using Docker: A Complete Step-by-Step Guide

Introduction

Have you ever developed an application that worked perfectly on your local machine but behaved differently when deployed to a server?
This is a common challenge for developers. Differences in operating systems, runtime versions, dependencies, and configurations can lead to unexpected deployment problems.
Docker helps address these challenges by packaging an application and its dependencies into a portable container image.
In this tutorial, we will deploy a Node.js application on an Amazon EC2 instance using Docker. We will also learn how to update the application, restart containers, and troubleshoot common deployment issues.
By the end, you will understand the basic workflow of deploying a containerized application to AWS.

1. Understanding the Architecture

Our deployment will follow this workflow:
Developer → GitHub → Amazon EC2 → Docker Container → Node.js Application → End User
Here is what each component does:
  • GitHub: Stores and manages application source code.
  • Amazon EC2: Provides a virtual machine where our application runs.
  • Docker: Packages and executes the application inside a container.
  • Node.js: Runs our backend application.
  • Security Group: Controls which network connections can reach our EC2 instance.
For this tutorial, we will deploy a simple Express application on port 3000 inside a container and expose it through port 80 on the EC2 host.

2. Prerequisites

Before starting, make sure you have:
  • An active AWS account.
  • Basic familiarity with Linux commands.
  • A Node.js application stored in GitHub.
  • An SSH key pair or another supported way to connect to EC2.
  • Basic knowledge of Git and Docker.
An AWS EC2 instance may incur charges depending on your configuration and account eligibility. Review AWS pricing before launching resources.

3. Launch an Amazon EC2 Instance

Sign in to the AWS Management Console and open the EC2 service.
Select Launch Instance and configure the following:
Instance Name:  nodejs-docker-server 
Amazon Machine Image: Amazon Linux 2023
Instance Type: Select an appropriately sized instance based on your application and account's pricing or free-tier eligibility.
Key Pair: Create a new key pair or select an existing one.
Network Configuration:
Use a subnet with internet connectivity and assign a public IP address if you want to access the instance directly from the internet.
Configure the security group:
Type
Port
Source
SSH
22
Your IP address
HTTP
80
0.0.0.0/0
Restrict SSH access to trusted IP addresses instead of exposing it to the entire internet.
Launch the instance and wait until it is running.

4. Connect to the EC2 Instance

On your local Linux or macOS terminal, set appropriate permissions on your private key:
chmod 400 my-key.pem
Connect to the EC2 instance:
ssh -i my-key.pem ec2-user@YOUR_PUBLIC_IP
Replace  YOUR_PUBLIC_IP  with the public IPv4 address of your EC2 instance.
Once connected, you can install the tools required for deployment.

5. Install Docker on Amazon Linux 2023

First, update the system packages:
sudo dnf update -y
Install Docker:
sudo dnf install -y docker
Start and enable the Docker service:
sudo systemctl enable --now docker
Verify that Docker is running:
sudo systemctl status docker
Add the current EC2 user to the Docker group:
sudo usermod -aG docker ec2-user
Log out and reconnect to apply the new group membership.
Verify the installation:
docker --version
docker ps
Security note: Membership in the Docker group grants powerful privileges, effectively equivalent to root access. Only trusted administrators should belong to this group.

6. Create a Simple Node.js Application

For demonstration, our application uses Express.
Create a project folder:
mkdir nodejs-docker-app
cd nodejs-docker-app
Initialize Node.js:
npm init -y
npm install express
Create a file named  server.js :
const express = require("express");

const app = express();
const PORT = process.env.PORT || 3000;

app.get("/", (req, res) => {
res.json({
message: "Hello from AWS EC2 and Docker!",
status: "running"
});
});

app.listen(PORT, "0.0.0.0", () => {
console.log(`Server running on port ${PORT}`);
});
Update the scripts section of  package.json :
"scripts": {
"start": "node server.js"
}
Test the application locally:
npm start
Open  http://localhost:3000 .
You should receive a JSON response confirming that the application is running.

7. Create a Dockerfile

A Dockerfile contains the instructions Docker uses to build an application image.
Create a file named  Dockerfile  in the project root:
FROM node:22-alpine

WORKDIR /app

COPY package*.json ./

RUN npm ci --omit=dev

COPY . .

EXPOSE 3000

USER node

CMD ["npm", "start"]
Explanation:
  •  FROM  selects the Node.js base image.
  •  WORKDIR  sets the working directory inside the container.
  •  COPY  transfers the required files into the image.
  •  RUN npm ci  installs production dependencies using the lockfile.
  •  EXPOSE  documents the application's listening port.
  •  USER node  runs the application as a non-root user.
  •  CMD  defines the startup command.
Because  npm ci  requires a lockfile, make sure  package-lock.json  is committed to your repository.
Create a  .dockerignore  file:
node_modules
.git
.env
npm-debug.log
This helps keep unnecessary files and local secrets out of the Docker build context.

8. Upload the Application to GitHub

Initialize Git and push your project to a repository:
git init
git add .
git commit -m "Initial Docker deployment"
Connect the local repository to your GitHub repository and push the code.
Make sure sensitive files, API keys, and credentials are never committed.

9. Clone the Project on EC2

Install Git on your EC2 instance:
sudo dnf install -y git
Clone your repository:
git clone https://github.com/YOUR_USERNAME/YOUR_REPOSITORY.git
Navigate to the project directory:
cd YOUR_REPOSITORY
Replace the placeholders with your actual repository details.

10. Build the Docker Image

Build the container image:
docker build -t nodejs-aws-app:v1 .
Here:
  •  docker build  creates the image.
  •  -t  assigns an image name and tag.
  •  .  specifies the current folder as the build context.
Verify the image:
docker images
Your newly built image should appear in the list.

11. Run the Docker Container

Start the application:
docker run -d \
--name nodejs-container \
--restart unless-stopped \
-p 80:3000 \
nodejs-aws-app:v1
The command performs several actions:
  •  -d  runs the container in the background.
  •  --name  assigns a readable name.
  •  --restart unless-stopped  configures automatic recovery after supported restarts.
  •  -p 80:3000  maps EC2 port 80 to container port 3000.
Check whether the container is running:
docker ps
View the application logs:
docker logs nodejs-container
Visit:
http://YOUR_PUBLIC_IP
If the deployment is successful, the browser should display the application's JSON response.
Congratulations! Your first Dockerized Node.js application is running on AWS EC2.

12. Update the Application After Code Changes

Now suppose you have updated your Node.js application and pushed the changes to GitHub.
To deploy the updated application, connect to EC2 and navigate to the repository.
Pull the latest changes:
git pull origin main
Build a new Docker image:
docker build -t nodejs-aws-app:v2 .
Stop the old container:
docker stop nodejs-container
Remove the old container:
docker rm nodejs-container
Run the updated image:
docker run -d \
--name nodejs-container \
--restart unless-stopped \
-p 80:3000 \
nodejs-aws-app:v2
Verify the new deployment:
docker ps
docker logs nodejs-container
This is a simple manual deployment workflow. It introduces downtime while replacing the running container, so more advanced deployment strategies are preferable for production applications.
Important distinction:  docker restart  restarts the existing container. It does not update its application code or replace the image. To deploy a newly built image, you must recreate the container.

13. Useful Docker Commands

These commands are helpful when operating a Docker-based application:
List running containers:
docker ps
List all containers:
docker ps -a
Check application logs:
docker logs -f nodejs-container
Restart a running application container:
docker restart nodejs-container
Inspect container resource usage:
docker stats
View Docker images:
docker images
Stop a container:
docker stop nodejs-container
Understanding these commands makes troubleshooting and day-to-day maintenance much easier.

14. Common Deployment Problems

Problem 1: Website Is Not Accessible

Possible causes include:
  • Port 80 is not allowed in the EC2 security group.
  • The container has stopped.
  • The application is listening on the wrong interface.
  • The container port mapping is incorrect.
Check:
docker ps
docker logs nodejs-container
Also verify the EC2 security group, public IP address, and subnet routing.

Problem 2: Docker Permission Denied

You may see an error indicating that your user cannot connect to the Docker daemon.
If you added  ec2-user  to the Docker group, disconnect and reconnect to your instance so the new group membership takes effect.

Problem 3: Application Works Locally but Not in Docker

Check that:
  • The correct port is configured.
  • The application listens on  0.0.0.0 .
  • Required dependencies are installed.
  • Environment variables are supplied correctly.

Problem 4: Updated Code Is Not Visible

Restarting an existing container does not rebuild the application image.
Pull the code, rebuild the image, and recreate the container using the new image.

15. Improvements for Production Deployments

Our example is suitable for understanding the deployment process, but production systems need additional safeguards.
HTTPS: Use a domain name and an HTTPS-enabled reverse proxy or load balancer with a trusted certificate.
Secrets Management: Store sensitive application secrets securely, such as through AWS Systems Manager Parameter Store or AWS Secrets Manager.
Monitoring: Use Amazon CloudWatch to collect application logs and infrastructure metrics.
CI/CD: Use GitHub Actions or Jenkins to automate building, testing, and deployment.
Image Management: Consider Amazon Elastic Container Registry (Amazon ECR) for securely storing container images.
Reliability: Configure health checks, backups, and a tested rollback process.
Security: Keep dependencies and container base images updated, restrict network access, and avoid unnecessary privileged access.
These improvements help move an experimental deployment toward a more reliable operational environment.

16. What I Learned

Working with Docker and EC2 highlights an important DevOps principle: deployment is not just about running an application.
A useful deployment workflow should be repeatable, understandable, observable, and secure.
Docker provides consistency through container images, while EC2 offers flexibility and control over the underlying server.
However, containerization is only one part of the overall process. Network configuration, permissions, logs, security, and operational procedures are equally important.

Conclusion

In this article, we explored how to deploy a Node.js application on AWS EC2 using Docker.
We covered everything from launching an EC2 instance and installing Docker to building images, running containers, updating deployments, and troubleshooting common problems.
This approach provides a useful starting point for learning cloud deployment and container-based application management.
As a next step, the same workflow can be extended with GitHub Actions, Jenkins, Amazon ECR, monitoring tools, and automated release pipelines.
What deployment challenges have you faced while working with Docker and AWS EC2? Share your experience in the comments!



References

Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article