Deploy a Node.js App to EC2 using Ansible

3 min read

🎯 Objective
Use Ansible to automate deploying a basic Node.js app on an EC2 instance running Amazon Linux 2.
🧰 Tools Used
Amazon Linux 2 EC2
Ansible
Node.js
Git (optional)
SSH
🛠️ Basic Node.js App Code (Use this)
Create a folder on your Ansible controller named nodejs-basic-app
and add these files:
index.js
const http = require('http');
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.end('Hello from Node.js App deployed using Ansible!');
});
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
package.json
{
"name": "nodejs-basic-app",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node index.js"
}
}
🪜 Step-by-Step Instructions
1️⃣ Prepare Target EC2 Instance
Launch Amazon Linux 2 EC2
Enable port 3000 in the Security Group
Allow SSH access from your Ansible controller
2️⃣ Install Ansible on Controller (if not installed)
sudo yum update -y
sudo amazon-linux-extras enable ansible2
sudo yum install ansible -y
3️⃣ Create Ansible Inventory
inventory.ini
[nodejs]
target-ec2 ansible_host=YOUR_EC2_PUBLIC_IP ansible_user=ec2-user ansible_ssh_private_key_file=~/.ssh/your-key.pem
4️⃣ Create Ansible Playbook
deploy-nodejs.yml
- name: Deploy Basic Node.js App
hosts: nodejs
become: yes
tasks:
- name: Install Git and Node.js
shell: |
yum install -y git
curl -sL https://rpm.nodesource.com/setup_16.x | bash -
yum install -y nodejs
args:
executable: /bin/bash
- name: Copy App Files to EC2
copy:
src: ./nodejs-basic-app
dest: /home/ec2-user/nodejs-basic-app
owner: ec2-user
group: ec2-user
mode: 0755
- name: Install npm dependencies
shell: npm install
args:
chdir: /home/ec2-user/nodejs-basic-app
- name: Start the Node.js app
shell: nohup node index.js &
args:
chdir: /home/ec2-user/nodejs-basic-app
5️⃣ Run the Playbook
ansible-playbook -i inventory.ini deploy-nodejs.yml
🔍 What You Learn Today
Install Node.js on Amazon Linux
Use Ansible to copy files and automate deployment
Run a basic app on EC2, accessible via
http://<EC2-PUBLIC-IP>:3000
🧠 How It Works
Step | Task Description | Purpose |
1️⃣ | Launch Amazon Linux EC2 and open port 3000 | Prepares target server to host the app |
2️⃣ | Install Ansible on controller machine | Enables automation from local or another EC2 |
3️⃣ | Define inventory with EC2 IP and SSH key | Tells Ansible where and how to connect |
4️⃣ | Create playbook to install Node.js & Git | Ensures target machine is ready for the app |
5️⃣ | Copy Node.js app files to EC2 | Transfers your app to the remote server |
6️⃣ | Install dependencies with npm install | Prepares app for running |
7️⃣ | Start app using nohup in background | Runs app so it stays alive after SSH logout |
✅ | Access app via http://<ec2-ip>:3000 | Verify it's working in browser |
0
Subscribe to my newsletter
Read articles from Suneel Kumar Kola directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
