Node.js Application Server

Sets up Node.js with PM2 process manager for production applications

Script Author

Rowan de Haas's avatar
Rowan de Haas
Script Author

Script Details

Created 10 months ago
Size 1 KB

Tags

Script Content

Raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#cloud-config
package_update: true
package_upgrade: true

packages:
  - curl
  - git
  - build-essential

write_files:
  - path: /etc/systemd/system/nodeapp.service
    content: |
      [Unit]
      Description=Node.js App
      After=network.target
      
      [Service]
      Type=simple
      User=nodeapp
      WorkingDirectory=/opt/nodeapp
      ExecStart=/usr/bin/node app.js
      Restart=on-failure
      RestartSec=10
      Environment=NODE_ENV=production
      
      [Install]
      WantedBy=multi-user.target

users:
  - name: nodeapp
    system: true
    shell: /bin/false
    home: /opt/nodeapp

runcmd:
  # Install Node.js 18.x
  - curl -fsSL https://deb.nodesource.com/setup_18.x | bash -
  - apt-get install -y nodejs
  # Install PM2 globally
  - npm install -g pm2
  # Create app directory
  - mkdir -p /opt/nodeapp
  - chown nodeapp:nodeapp /opt/nodeapp
  # Setup PM2 startup script
  - pm2 startup systemd -u nodeapp --hp /opt/nodeapp

How to Use This Script

Cloud Provider Examples

Amazon EC2

aws ec2 run-instances
  --image-id ami-12345678
  --instance-type t3.micro
  --user-data file://script.yaml

DigitalOcean

doctl compute droplet create
  --image ubuntu-22-04-x64
  --size s-1vcpu-1gb
  --user-data-file script.yaml
  my-droplet

Google Cloud

gcloud compute instances create
  my-instance
  --metadata-from-file
  user-data=script.yaml