October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
Blog

How to Deploy a Node.js App with Terraform on a Linux VPS

Use Terraform to create the VPS and network, cloud-init to bootstrap it, systemd to keep Node.js running, and NGINX to proxy public traffic safely.
Length11 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The reliable pattern is to let Terraform create the Linux VPS, SSH association, firewall rules, and public address; pass a cloud-init document in the provider’s startup-data field; then let cloud-init install Node.js and NGINX, create a non-root service account, install your application, and register a systemd service. NGINX exposes ports 80 and 443 and proxies privately to Node.js on 127.0.0.1:3000. systemd keeps the process running after you disconnect from SSH, restarts it after a failure, and starts it again after a reboot.

Terraform is the infrastructure lifecycle tool in this design, not the Node.js process manager. Use provisioners only when startup data, an image, or configuration management cannot perform a narrowly defined post-apply task.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What the deployment contains

A production-shaped single-VPS deployment has five layers:

  1. Terraform: declares the VPS, network dependencies, firewall policy, SSH key association, and address.
  2. cloud-init: runs on first boot, updates packages, installs Node.js/npm and NGINX, creates the deploy account, writes configuration, and enables services.
  3. systemd: runs the Node.js application as a dedicated user with restart and boot policies.
  4. NGINX: listens on the public web ports and forwards requests to the private Node.js listener.
  5. Verification and operations: health checks, logs, controlled updates, and a tested destroy path.

HashiCorp describes cloud-init as a standard configuration tool available on most Linux distributions and major cloud providers. The cloud-init project calls it the industry-standard, multi-distribution method for initializing cloud instances. It is therefore a better first-boot bridge than making Terraform open an SSH session to every new server.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

Decide the provider-specific pieces first

Terraform syntax for a VPS resource, firewall, SSH-key attachment, and public-address output differs by provider. Before writing the module, choose the exact provider, region, Linux distribution, and supported Node.js LTS line. Record those decisions in version control rather than relying on floating defaults.

Provider and region

Compare the regions where your users are located, IPv4 and IPv6 availability, included bandwidth and traffic limits, snapshots or backups, firewall controls, provider support, Terraform provider quality, and the complete monthly cost. These properties change by geography and over time, so obtain current values from the provider’s documentation before committing to a region.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Operating system and Node.js

Use a distribution with a supported security-update channel. Debian- or Ubuntu-family systems commonly use apt; Red Hat-family systems use different package commands and service conventions. Install a supported Node.js LTS release from the distribution or a trusted vendor repository, and pin the major line required by your application. The application’s engines field and lockfile should be the authority for the exact runtime.

Network policy

Allow SSH only from your administrative address range. Allow HTTP and HTTPS publicly if the application is public. Do not expose port 3000: NGINX should be the only public entry point, while Node.js binds to localhost. Apply the policy in the provider firewall or security-group resource, then verify it from an external network.

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

Prepare a small Terraform project

Keep infrastructure and bootstrap files together, for example:

node-vps/
  main.tf
  variables.tf
  outputs.tf
  cloud-init.yaml
  terraform.tfvars

Install the Terraform CLI on your workstation, configure the selected provider and credentials using that provider’s documented method, and keep credentials out of source control. A typical workflow is:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. terraform init downloads the provider and initializes the backend.
  2. terraform fmt -check checks formatting.
  3. terraform validate checks configuration and types.
  4. terraform plan previews creation, replacement, and network changes.
  5. terraform apply creates or updates the declared infrastructure.

Use a protected remote backend for team work, enable state locking when the backend supports it, and restrict access to the state file. State can contain sensitive values even when your source code does not. Never place private SSH keys, application secrets, or long-lived provider tokens directly in Terraform files. Pass only the startup data and references that the provider requires, and use a secret-management mechanism appropriate to your provider for production secrets.

Attach cloud-init through startup data

Most VPS resources expose a field named user_data, custom_data, or an equivalent startup-data argument. Keep the YAML in a separate file and load it from Terraform:

Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)
locals {
  cloud_init = file("${path.module}/cloud-init.yaml")
}

Set the selected VPS resource’s startup-data field to local.cloud_init. The resource block, image identifier, size, network arguments, and firewall syntax must come from your provider’s current Terraform documentation; do not copy a resource type from another provider. Export the provider’s assigned public IPv4 or hostname in outputs.tf so operators do not have to search the control panel after every apply.

Use cloud-init for first-boot configuration

The following Debian/Ubuntu-oriented example is intentionally self-contained. It creates a tiny Node.js HTTP service so the deployment can be tested without inventing a repository URL. Replace the sample files with your built application or image-baked release before production use. If your project includes a lockfile, the script uses npm ci --omit=dev; otherwise it falls back to the documented production install command.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#cloud-config
package_update: true
package_upgrade: true
packages:
  - nodejs
  - npm
  - nginx

write_files:
  - path: /opt/nodeapp/package.json
    owner: root:root
    permissions: '0644'
    content: |
      {"name":"nodeapp","private":true,"scripts":{"start":"node server.js"}}
  - path: /opt/nodeapp/server.js
    owner: root:root
    permissions: '0644'
    content: |
      const http = require('http');
      const port = Number(process.env.PORT || 3000);
      http.createServer((req, res) => {
        if (req.url === '/health') {
          res.writeHead(200, {'Content-Type': 'application/json'});
          return res.end(JSON.stringify({status: 'ok'}));
        }
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('Node.js app is runningn');
      }).listen(port, '127.0.0.1');
  - path: /etc/nodeapp/nodeapp.env
    owner: root:root
    permissions: '0640'
    content: |
      NODE_ENV=production
      PORT=3000
  - path: /etc/systemd/system/nodeapp.service
    owner: root:root
    permissions: '0644'
    content: |
      [Unit]
      Description=Node.js application
      After=network.target

      [Service]
      Type=simple
      User=nodeapp
      Group=nodeapp
      WorkingDirectory=/opt/nodeapp
      EnvironmentFile=/etc/nodeapp/nodeapp.env
      ExecStart=/usr/bin/node /opt/nodeapp/server.js
      Restart=on-failure
      RestartSec=5

      [Install]
      WantedBy=multi-user.target
  - path: /etc/nginx/sites-available/nodeapp
    owner: root:root
    permissions: '0644'
    content: |
      server {
          listen 80;
          listen [::]:80;
          server_name _;
          location / {
              proxy_pass http://127.0.0.1:3000;
              proxy_http_version 1.1;
              proxy_set_header Host $host;
              proxy_set_header X-Real-IP $remote_addr;
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
              proxy_set_header X-Forwarded-Proto $scheme;
          }
      }

runcmd:
  - [useradd, --system, --create-home, --home-dir, /home/nodeapp, --shell, /usr/sbin/nologin, nodeapp]
  - [mkdir, -p, /etc/nodeapp, /opt/nodeapp]
  - [chown, -R, nodeapp:nodeapp, /opt/nodeapp]
  - [bash, -c, 'if [ -f /opt/nodeapp/package-lock.json ]; then npm ci --omit=dev --prefix /opt/nodeapp; else npm install --omit=dev --prefix /opt/nodeapp; fi']
  - [ln, -sfn, /etc/nginx/sites-available/nodeapp, /etc/nginx/sites-enabled/nodeapp]
  - [rm, -f, /etc/nginx/sites-enabled/default]
  - [systemctl, daemon-reload]
  - [systemctl, enable, --now, nodeapp.service]
  - [nginx, -t]
  - [systemctl, enable, --now, nginx]

For a real release, deliver the application files before the npm command runs. Common approaches are baking the release into a machine image, having cloud-init unpack an artifact supplied through a provider-supported mechanism, or using a separate configuration-management/deployment system. Do not put a private repository token in the YAML or Terraform state. If your distribution installs Node.js somewhere other than /usr/bin/node, update ExecStart to the actual path.

Why the unit file matters

WorkingDirectory makes relative paths deterministic. EnvironmentFile keeps runtime settings outside the unit definition and allows a permissions-restricted file. User=nodeapp prevents the application from running as root. Restart=on-failure handles crashes without hiding a clean administrative stop, and WantedBy=multi-user.target makes the service start during normal boot.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

Why NGINX stays in front

Node.js remains bound to localhost, so the firewall never needs to expose port 3000. NGINX owns the public listener and forwards the original host, client address, and protocol headers. TLS termination, certificate automation, request limits, and static-file rules can be added at NGINX without changing the application listener.

Apply and wait for first boot

Run the formatting, validation, and plan checks before applying. After terraform apply reports the address, do not assume the application is immediately ready. cloud-init starts after the VM is provisioned and may need several minutes before SSH and the service are available.

  1. Connect with the intended non-root administrative user: ssh user@PUBLIC_IP. The exact username comes from the selected image and your SSH-key configuration.
  2. Wait for initialization with sudo cloud-init status --wait. On distributions without that command, use the distribution’s equivalent status mechanism.
  3. Confirm the runtime: node --version and npm --version.
  4. Check the service: systemctl is-enabled --quiet nodeapp.service and systemctl is-active --quiet nodeapp.service.
  5. Test locally on the VPS: curl -fsS http://127.0.0.1:3000/health.
  6. Validate NGINX with sudo nginx -t, then test externally with curl -i http://PUBLIC_IP/health or your DNS name.

Use journalctl -u nodeapp.service for application logs and the NGINX error log for proxy failures. Keep the Node.js port private while allowing only the required public ports through the provider firewall.

Keep Node.js running after SSH disconnects

Do not start production Node.js with node server.js in an interactive SSH shell. That process is tied to the session and has no boot, restart, or log policy. The systemd unit is independent of your terminal: once enabled, it starts at boot; once active, it survives your SSH disconnect; and when the process exits unsuccessfully, systemd retries it after the configured delay.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.

Use sudo systemctl restart nodeapp.service for a controlled restart, sudo systemctl stop nodeapp.service for maintenance, and sudo systemctl status nodeapp.service for a concise diagnostic view. A clean stop should remain stopped; repeated crash loops should be investigated rather than masked with an aggressive restart policy.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Cloud-init, images, configuration management, and provisioners

Choose the mechanism that matches the lifecycle you need:

Method Repeatability Network reachability Drift and rollback Debugging profile
cloud-init startup data Runs consistently on first boot from the declared VM definition Does not require Terraform to reach the guest after creation Good for immutable replacement; changes normally require a new instance or an explicit in-guest update Inspect cloud-init status and logs on the VM
Machine image Fast and highly repeatable when the image pipeline is controlled Guest access is unnecessary during boot Rollback is selecting a previous image version Debug the image build as well as first-boot configuration
Configuration management Designed for recurring convergence and larger fleets Usually needs an agent, control channel, or reachable management endpoint Handles drift better than one-time bootstrap when applied regularly Centralized tooling can improve diagnostics but adds another system
Terraform provisioner Less predictable because scripts run outside Terraform’s resource model Usually requires direct SSH or another connection from the workstation or runner Replacement, retries, and partial failure behavior need explicit design Failures commonly fail terraform apply; inspect both Terraform output and guest logs

HashiCorp recommends provider-native startup data, cloud-init, images, or configuration management before provisioners. Its guidance emphasizes that Terraform is designed primarily for immutable infrastructure and that purpose-built tools are preferable for provisioning software.

When a provisioner is justified

Terraform provides local-exec, remote-exec, and file provisioners. Use one only for a narrowly bounded post-apply action that the provider, image, cloud-init, or configuration-management tool cannot perform. Remote execution needs a connection block, commonly SSH; scripts run in declaration order, and a failed provisioner normally fails the apply.

  • Make the script idempotent: a second run should converge rather than duplicate users, files, or services.
  • Use a dedicated or ephemeral deployment key and restrict its source addresses and permissions.
  • Document what happens when the VPS is replaced, when the runner cannot reach SSH, and when a retry follows a partial run.
  • Keep secrets out of command-line arguments and Terraform state.

Updates, replacement, and rollback

For an immutable workflow, build a new image or startup-data version, create a replacement VPS, verify its health endpoint and public proxy, then switch the address or DNS according to your provider’s capabilities. This gives a clean rollback: return traffic to the previous healthy instance while investigating the new one.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For an in-place update, upload the new release to a versioned directory, install production dependencies, adjust the systemd working path or symlink, run the health check locally, and restart the unit. Keep the previous release until the new one passes verification. Terraform should continue to own infrastructure changes; do not edit firewall rules or the public address manually and expect Terraform state to understand the drift.

Security and operations checklist

  • Use a non-root deploy or service user and disable unnecessary interactive access for that account.
  • Expose SSH only to an administrative range; expose HTTP/HTTPS publicly only when required.
  • Keep Node.js on localhost and let NGINX handle public traffic.
  • Apply security updates during image building or first boot, then define how ongoing patching will occur.
  • Protect remote Terraform state and review every planned change.
  • Keep environment files readable only by root and the service account; use an external secret store for high-value credentials.
  • Retain application and NGINX logs long enough to investigate crashes and failed deployments.
  • Test restoration from snapshots or backups rather than assuming they work.

Troubleshooting common failures

Symptom Checks Likely correction
SSH times out immediately after apply Confirm the public address, provider firewall, image username, and cloud-init completion Wait for first boot, allow SSH from your administrative range, and use the image’s documented user
cloud-init reports failure Run cloud-init status --long and inspect its logs Fix YAML indentation, package names, or command ordering; recreate the VPS when a clean first boot is required
systemd is inactive Run systemctl status nodeapp.service and journalctl -u nodeapp.service Check ExecStart, the Node.js path, file ownership, environment variables, and the application’s start command
Local health check works but public HTTP fails Run nginx -t, inspect the NGINX error log, and verify ports 80/443 in the provider firewall Correct the server block, enable the site, or open only the required public ports
npm ci fails Check whether a lockfile exists and whether its package-manager version matches the project Commit the correct lockfile or use the project’s documented production installation command
Service works until reboot Check systemctl is-enabled nodeapp.service and NGINX Enable both units and confirm the unit has an [Install] target

Destroy disposable environments deliberately

For a test VPS, run terraform destroy after collecting the logs or snapshot you need. HashiCorp’s tutorial demonstrates destroying a test instance to avoid ongoing charges. In a production workspace, protect the state and require review before destroy; verify that backups, DNS, and replacement capacity are handled before approving it.

Final deployment sequence

  1. Select and pin the provider, region, Linux image, and Node.js LTS line.
  2. Declare the VPS, SSH association, firewall, and address in Terraform.
  3. Pass cloud-init through the provider’s startup-data field.
  4. Install the app as a non-root user, run its production dependency install, and register systemd.
  5. Proxy NGINX to 127.0.0.1:3000; never expose the Node.js port publicly.
  6. Apply, wait for cloud-init, verify systemd, test the health endpoint externally, and inspect logs.
  7. Use immutable replacement or a documented in-place release process for updates, and reserve provisioners for exceptional cases.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.