Systemd is a suite of basic building blocks for a Linux system. It provides a system and service manager that runs as PID 1 and starts the rest of the system. There are cases that you want to run a script or job on a Linux server and keep track of the logs without an external library and also get the benfit of seamless control over the application lifecycle on the server. Systemd provides all of this out of the box. In this simple example I tried to demonstrate the use case with a simple Express hello world server that is developed in Typescript and TS-Node.
- Nodejs
- NPM
You need to install Node in your Linux server and then install ts-node package:
# Or globally with TypeScript.
npm install -g typescript
npm install -g ts-node
Create a directory at /usr/local/
for your app. you may need admin permission:
mkdir /usr/local/hello-world
Then change your direcotry to:
cd /usr/local/hello-world
You need to initialize your node project and install express library:
npm init -y
npm i express
npm i -D @types/express
you need to create index.ts
file and copy/paste the content of the file into it. we are set with the script but
we also need to create systemd service:
touch /etc/systemd/system/hello-world.service
and then copy/paste the content of hello-server.service
file into it.
We are also set with systemd service configruation.
You are now able to execute the server under systemd services and control the status with systemd commands.
systemctl daemon-reload
systemctl enable hello-world.service
systemctl start hello-world.service
We can easily check logs for the service in real-time via journalctl:
journalctl -u hello-world.service -f
You should see something like bellow if you send curl localhost:3000/elias?github=fractalliter
:
Apr 28 20:36:44 user-something systemd[1]: Started Hello world server.
Apr 28 20:36:46 user-something ts-node[21800]: Server running at PORT: 3000
Apr 28 20:36:57 user-something ts-node[21800]: request received param elias that queries {"github":"fractalliter"}
JournalCTL enables us to query the logs between dates and for specific log level like error
or info
.