info@equalefforts.com

Technology

How to Run a Socket.IO Server as a Systemd Service on Ubuntu 24.04

Problem

Why does the Socket.IO server stop running when the terminal is closed?

Solution

Configure and run the Socket.IO server as a systemd service to ensure it remains active after terminal closure.

Prerequisites

  • Ensure that you have installed Node.js globally on your system.
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash - sudo apt install -y nodejs
  • curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash – sudo apt install -y nodejs
  • Create a Node.js app (if not already done)
  • Make sure your socket.io server is a Node.js script. For example: /home/<User_name>/socket-server/server.js.
  • Also, make sure it’s executable with node:
node /home/<User_Name>/socket-server/server.js

Here’s how to do it step-by-step

Step 1: Create a systemd service file

Run this command to create a socketio.service file to your system

sudo nano /etc/systemd/system/socketio.service

Step 2: Paste this code into your service file

[Unit]
Description=Socket.IO Server
After=network.target

[Service]
ExecStart=/usr/bin/node /home/<USER_NAME>/socket-server/server.js
WorkingDirectory=/home/<USER_NAME>/socket-server
Restart=always
User=<USER_NAME>
Environment=NODE_ENV=[development/production]
StandardOutput=append:/home/<USER_NAME>/socket-server/socketio.log # Or you can use "syslog"
StandardError=append:/home/<USER_NAME>/socket-server/socketio-error.log # Or you can use "syslog"
SyslogIdentifier=socketio-server

[Install]
WantedBy=multi-user.target

Step 4: Ensure all .js files are treated as ES Modules in a development environment.

Add this parameter to your package.json: “type”: “module”

{
  "name": "liferay-chat",
  "version": "1.0.0",
  "type": "module",
  ...
}

Step 5: Reload systemd and enable the service

sudo systemctl daemon-reexec
sudo systemctl daemon-reload
sudo systemctl enable socketio.service
sudo systemctl start socketio.service

Step 6: Check the service status

sudo systemctl status socketio.service

You should see it’s running. You can now safely close the terminal, and your server will continue to run in the background.

Optional: View logs

journalctl -u socketio.service -f

Conclusion

Running your Socket.IO server as a systemd service ensures that it operates independently of any terminal session, providing greater reliability and uptime. This approach is essential for production environments, where services must automatically start on boot, recover from failures, and remain stable without manual intervention. By integrating your server with systemd, you gain better control, monitoring, and management of your Node.js applications.

Author

Jitin Jadavra

Leave a comment

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