Wednesday, 27 August 2025

Why PM2 Is Not Launching Your Node.js App—and How to Fix It

Why PM2 Is Not Launching Your Node.js App—and How to Fix It

Broken Your Node.js PM2 — and How to Fix It

Have you ever faced the frustration of manually running your Node.js app only for it to work perfectly—and yet, when launching it via PM2, it stubbornly refuses to respond? This is a surprisingly common issue, but fortunately, one that can often be resolved with a systematic approach.

In modern production environments, PM2 is a trusted manager for running Node.js processes reliably. But when things go wrong, it can feel like a black box—your app shows as “online” yet fails to respond. This blog will walk you through the most frequent culprits, structured troubleshooting steps, and production-level hardening tips to ensure your app stays up and running smoothly.

Common Reasons PM2 Fails to Launch Your Node Process

  • Script Path or Filename Errors: A misconfigured script path may lead to silent failures. Verify file references like server/index.js.
  • Application Not Listening on the Expected Port: Ensure your app is binding and listening on the correct port.
  • Daemon Mode & Execution Context (Especially on Windows): GUI apps may not launch correctly without the --no-daemon flag.
  • Missing System Startup Configuration: Without running pm2 startup and enabling systemd, apps won’t auto-start on reboot.
  • Node Version Mismatch: After Node upgrades (e.g., via NVM), reinstall and update PM2 to maintain compatibility.
  • Cluster Mode Port Conflicts: Avoid EADDRINUSE errors by assigning unique ports or using fork mode.

Step-by-Step Troubleshooting Guide

  1. Verify Script Path & Logging
    Use pm2 logs and pm2 show <app> to inspect the app’s status and confirm the script path.
  2. Confirm App is Listening on the Correct Port
    Use netstat, lsof, or curl to ensure the app binds to the expected port.
  3. Use --no-daemon if Needed
    Launch with pm2 start app.js --no-daemon on systems that require GUI compatibility.
  4. Configure System Startup Properly
    Run:
    pm2 startup
    # Follow systemd instructions
    pm2 save
  5. Reinstall PM2 After Node Updates
    After switching Node versions, reinstall PM2 and run pm2 update.
  6. Avoid Port Conflicts in Cluster Mode
    Assign unique ports or switch to fork mode to prevent errors.

Best Practices for Production Stability

  • Use ecosystem.config.js to define mode, port, memory limits, and restart policies.
  • Implement logging and health checks using --watch, --max-memory-restart, and structured formats.
  • Integrate monitoring tools like ELK, Better Stack, or CloudWatch.
  • Ensure proper handling of unhandled promise rejections to avoid silent crashes.

FAQs

  • Why does PM2 say my app is “online,” but it’s not responsive?
    Likely due to incorrect port binding or silent failure in the startup routine.
  • How do I make PM2 launch my app after reboot?
    Use pm2 startup followed by pm2 save to persist processes.
  • Why won’t my GUI Node app start with PM2?
    Try --no-daemon or start via npm scripts.
  • What should I do after upgrading Node?
    Reinstall PM2 and run pm2 update to sync versions.

Conclusion

When PM2 isn’t launching your Node.js app, the root cause is usually in environment or configuration. Use this guide to diagnose script path errors, port issues, version mismatches, and system startup configs. With proper setup, PM2 becomes an indispensable tool for Node.js app stability.

Monday, 11 August 2025

Reconnect Magic Mouse Without a Cable: The Quick Keyboard Shortcut Method

 


If you’ve ever had your Apple Magic Mouse suddenly disconnect while working, you know the frustration—especially if you don’t have a Lightning cable handy. For many Mac users, reconnecting without a mouse feels impossible. But here’s the good news: you can reconnect your Magic Mouse without a cable using a quick keyboard shortcut method.

This guide will show you how to navigate macOS entirely from your keyboard, restore your Bluetooth connection in seconds, and keep your workflow moving—no desk rummaging or cable hunts required.


Why This Shortcut Works

macOS includes built-in features that let you control your Mac entirely with the keyboard, including accessing system tools like Bluetooth File Exchange. By combining these with accessibility settings, you can quickly re-pair your Magic Mouse when it drops the connection.

This method is:

  • Cable-free – no need for a Lightning cable.

  • Fast – reconnect in under a minute.

  • Practical – works anywhere, even if you have no spare peripherals.





Step-by-Step Keyboard Method

Step 1: Launch Bluetooth File Exchange

  • Press Command (⌘) + Space to open Spotlight.

  • Type Bluetooth File Exchange and hit Return.

  • If Bluetooth is off, macOS will prompt you to turn it on—press Return again to confirm.

Step 2: Prepare Your Magic Mouse

  • Flip the switch on the bottom of the mouse to turn it off and on again, putting it in pairing mode.

Step 3: Navigate to Bluetooth Settings

  • Press Command (⌘) + Space, type Bluetooth, and hit Return.

  • Use arrow keys to select your Magic Mouse from the device list, then press Return to connect.


Alternate Method via System Preferences

If the above doesn’t work, try this:

  1. Command (⌘) + Space, type Mouse, and hit Return.

  2. Enable Full Keyboard Access with Option + Command + F5.

  3. Use Tab to move focus to “Set Up Bluetooth Device,” then press Space to open pairing options.

  4. Select your Magic Mouse and press Return.


Bonus Tips for a Seamless Experience

  • Enable Full Keyboard Access permanently in System Settings > Accessibility > Keyboard to make navigation easier.

  • Reset Bluetooth module by holding Shift + Option while clicking the Bluetooth icon in the menu bar and choosing “Reset Bluetooth Module.”

  • If your mouse doesn’t appear, delete Bluetooth preferences (/Library/Preferences/com.apple.Bluetooth.plist) and restart.


Why This is a Game-Changer for Mac Users

This method saves you from downtime, keeps your workspace cable-free, and makes you less dependent on extra accessories. Whether you’re in a cafĂ©, on a flight, or just working from a couch, you can keep your workflow running without missing a beat.


FAQs

Q: How do I reconnect a Magic Mouse without a cable?
A: Use Spotlight (Command + Space) to open Bluetooth File Exchange, turn on Bluetooth, then pair your Magic Mouse from Bluetooth settings.

Q: What if my Magic Mouse doesn’t show up in Bluetooth settings?
A: Restart Bluetooth, toggle your mouse off/on, reset the Bluetooth module, or delete Bluetooth preference files.

Q: Can I do this on older Macs?
A: Yes, as long as you have Spotlight search and Bluetooth File Exchange installed (macOS Lion and later).



Conclusion

Losing your mouse connection doesn’t have to stop your productivity. With this quick keyboard method, you can reconnect your Apple Magic Mouse without a cable in under a minute—no stress, no slowdown. Try it next time and share this tip with fellow Mac users who might need it.


Friday, 7 February 2025

Resolving SFTP Import Failures on Amazon AWS: Best Practices for Cloud Development and SRE Engineering

In the fast‐paced world of Cloud Development and SRE Engineering, encountering transient errors can disrupt your workflow. Recently, our team noticed an error during an SFTP import job that failed at 2020-02-20

The error log indicated an AccessDenied issue when the Lambda function attempted to perform an s3:ListBucket operation on an S3 bucket (e.g. arn:aws:s3:::example-bucket). In this article, we will explore how to diagnose and resolve this issue using Amazon AWS–native techniques, offering insights and practical examples for engineers working in cloud environments.


Understanding the Issue

The Error Scenario

During an SFTP import job, our logs reported the following error:

AccessDenied: User: arn:aws:sts::111111xxxxxx:assumed-role/AxLambdaRole-user-envname/EventBusListenerFunction-envname-user is not authorized to perform: s3:ListBucket on resource: "arn:aws:s3:::example-bucket" because no identity-based policy allows the s3:ListBucket action
Status Code: 403
Request ID: RTDG456GRHUUO1

Our investigation revealed that the job was triggered twice:

  1. First Invocation (Failure): The job started when the SFTP stream began writing to the S3 bucket. At this point, the file was incomplete, and the Lambda function did not have permission to list the bucket.
  2. Second Invocation (Success): When the file upload finished, a subsequent trigger led to a successful run.

Team Discussion and Client Feedback

Our internal discussion concluded that the SFTP file was being streamed into the bucket. One of our SRE engineers proposed that the initial trigger occurred when the file stream began, and the second one when the stream completed. However, this double-triggering results in false-positive alerts, as the email notifications indicate.

The client explained:

"Cynthetic Client writes files directly to the SFTP server without first creating a local copy. Changing this behavior would require additional infrastructure and significant time to propose and approve an architectural change in the Data Platform."

They are exploring alternatives, but in the meantime, we need a solution that minimizes false alerts using existing Amazon AWS features.


Amazon AWS–Native Strategies to Resolve the Issue

Here are several strategies that leverage AWS-native services and configurations to address the issue without needing major infrastructure changes.

1. Refine S3 Event Notification Triggers

Use Specific Event Types:

  • Instead of triggering on every object creation event, configure your S3 bucket to send notifications only when the file upload is complete.
  • If your process uses multipart uploads, configure the event to trigger on the s3:ObjectCreated:CompleteMultipartUpload event.
  • Refer to the Amazon S3 Event Notifications documentation for more details.

Apply Object Key Filters:

  • Encourage your partners to add a specific suffix (e.g., .complete) to file names when the file is fully uploaded.
  • Update the event configuration to trigger only on objects that match this pattern.

2. Utilize SQS with Delayed Processing

Route Events Through an SQS Queue:

  • Instead of triggering the Lambda function directly from the S3 event, configure the bucket to send events to an Amazon SQS queue.
  • This allows you to introduce a delay or buffer time before processing the event.

Implement Delay or Validation in Lambda:

  • Within your Lambda function, add logic to check whether the file upload is complete by verifying object metadata (e.g., size or custom tags).
  • If the file is incomplete, the function can ignore the event or re-queue it for later processing.
  • Learn more about integrating SQS with Lambda in the AWS Lambda Developer Guide.

3. Adjust the IAM Policy for the Lambda Role (Temporary Workaround)

Grant s3:ListBucket Permission:

  • As a short-term measure, update the IAM policy attached to the Lambda’s role to allow s3:ListBucket on the S3 bucket.
  • This can prevent the Lambda function from failing the initial check.
  • However, note that even with the permission granted, if the file is incomplete, your processing logic may still encounter issues.
  • For more on IAM policies, refer to the AWS IAM User Guide.

4. Work with Your SFTP Partner

Discuss Alternative Upload Approaches:

  • Engage with your SFTP provider (in our case, Synthetic Client) and ask if they could temporarily stream the file to a staging area or use a naming convention to indicate when the file is fully uploaded.
  • Although the client mentioned that changing this process requires additional infrastructure and lengthy approvals, a dialogue might uncover interim solutions.

Example: Implementing an SQS-Delayed Lambda Trigger

Below is an example configuration for routing S3 events through SQS with a delay, minimizing false alerts.

  1. Configure S3 to Send Notifications to SQS:

  2. Set a Delay on the SQS Queue:

  3. Update Your Lambda Function:

    • Modify the Lambda code to check if the object exists in its complete form. For example, use the HeadObject API to verify file size or metadata.
    • Process the event only if the file meets the completeness criteria.

Conclusion

By refining your S3 event triggers, leveraging Amazon AWS services like SQS for delayed processing, and, if necessary, temporarily adjusting IAM policies, you can reduce false alarms caused by premature Lambda invocations during SFTP streaming uploads. This approach aligns with best practices in Cloud Development and SRE Engineering, ensuring your systems remain robust and secure without incurring significant additional costs.

For further reading, check out these official resources:

Implementing these solutions can help your team manage SFTP imports more reliably while reducing unwanted alerts. This method exemplifies how strategic configuration in Amazon AWS can streamline Cloud Development processes and enhance the operational efficiency expected in modern SRE Engineering practices.

Happy cloud developing!

Tuesday, 15 October 2024

How to check for open ports on Linux

Checking for open ports is among the first steps to secure your device. Listening services may be the entrance for attackers who may exploit service vulnerabilities to gain access or disrupt a system. 

A listening service or listening port is an open port with an application waiting for a client to connect (e.g an FTP server waiting for an FTP client) There is not sense in keeping a web server running if you aren’t serving a website, nor to keep the port 22 open if you don’t use ssh. 

This tutorial shows how to check for open ports both remotely and locally and how to close them.

How to check for open ports on Linux locally

The command netstat is present on all computer OS (Operating Systems) to monitor network connections. The following command uses netstat to show all listening ports using the TCP protocol:

netstat -lt

Where:
netstat: calls the program.
-l: lists listening ports.
-t: specifies TCP protocol.

The output is friendly, well ordered in columns showing the protocol, received and sent packets, local and remote IP addresses and the port state.

If you change the TCP protocol for UDP the result, at least on Linux, will display only open ports without specifying the state because contrary to the TCP protocol, the UDP protocol is stateless.

netstat -lu

You can avoid specifying protocols and use only the option -l or –listen to get information on all ports listening independently of the protocol:

netstat --listen

The option above will display information for TCP, UDP and Unix socket protocols.

All examples above show how to print information on listening ports without established connections. The following command shows how to display listening ports and established connections:

netstat -vatn

Where:
netstat: calls the program
-v: verbosity
-a: shows active connections.
-t: shows tcp connections
-n: shows ports in numerical value

Let’s say you identified a suspicious process in your system and you want to check associated ports to it. You can use the command lsof used to list open files associated to processes.

lsof -i 4 -a -p <Process-Numer>

In the next example I will check the process 19327:

lsof -i 4 -a -p 19327

Where:
lsof: calls the program
-i: lists files interacting with the internet, the option 4 instructs to print only IPv4, option 6 is available for IPv6.
-a: instructs the output to be ANDed.
-p: Specify the PID number of the process you want to check.

As you see the process is associated with the listening smtp port.

How to check for open ports on Linux remotely

If you want to detect ports on a remote system the most widely used tool is Nmap (Network Mapper). The following example shows a single port scan against Linuxhint.com:

nmap linuxhint.com

The output is ordered in 3 columns showing the port, the port state and the service listening behind the port.

Not shown: 988 closed ports
PORT           STATE         SERVICE
22/tcp         open          ssh
25/tcp         open          smtp
80/tcp         open          http
161/tcp        filtered      snmp
443/tcp        open          https
1666/tcp       filtered      netview-aix-6
1723/tcp       filtered      pptp
6666/tcp       filtered      irc
6667/tcp       filtered      irc
6668/tcp       filtered      irc
6669/tcp       filtered      irc
9100/tcp       filtered      jetdirect
By default, nmap scans the most common 1000 ports only. If you want Nmap to scan all ports run:

nmap -p- linuxhint.com
At the Related Articles section of this tutorial, you can find additional tutorials on Nmap to scan ports and targets with many additional options.

Removing services on Debian 10 buster

Additionally to firewall rules to keep your ports blocked removing unnecessary services is recommended. Under Debian 10 Buster this can be achieved with apt.
The following example shows how to remove the Apache 2 service using apt:

apt remove apache2

If requested press Y to end the removal.

How to close open ports on Linux using UFW


If you find open ports you don’t need to be open the easiest solution is to close it using UFW (Uncomplicated Firewall)

There are two ways to block a port, by using the option deny and with the option reject, the difference is the reject instruction will inform the second side the connection was rejected.

To block the port 22 using the rule deny just run:

ufw deny 22

To block the port 22 using the rule reject just run:

ufw reject 22


On the Related Articles section at the end of this tutorial, you can find a good tutorial on Uncomplicated Firewall.

How to close open ports on Linux using iptables

While UFW is the easiest way to manage ports, it is a frontend for Iptables.
The following example shows how to reject connections to the port 22 using iptables:

iptables -I INPUT -p tcp --dport 22 -j REJECT

The rule above instructs to reject all tcp incoming (INPUT) connections to destination port (dport) 22. Being rejected the source will be informed the connection was rejected.

The following rule just drops all packets without informing the source the connection was rejected:


iptables -A INPUT -p tcp --dport 22 -j DROP

I hope you found this brief tutorial useful. Keep following LinuxHint for additional updates and tips on Linux and Networking.

Why PM2 Is Not Launching Your Node.js App—and How to Fix It

Why PM2 Is Not Launching Your Node.js App—and How to Fix It Broken Your Node.js PM2 — and How to Fix It Have you ever...