On Thu, Mar 16, 2023 at 09:40:48AM +0800, cor...@free.fr wrote:
> On 16/03/2023 09:32, Greg Wooledge wrote:
> > If that's more than you want to tackle, and if all you want is
> > automatic restarting (not the ability to stop it at will), then this
> > should suffice:
> > 
> > #!/bin/sh
> > PATH=/whatver/you/need
> > while true; do
> >     serve -s /path/to/your/service
> >     sleep 5
> > done
> > 
> > Then arrange for this script to be executed at boot time, and that's it.
> > No background stuff, no polling from crontab.  Just a simple loop.
> 
> Thanks Greg. I will update with the way you gave.
> where will I setup this script for systemd job? any reference?

Well... see, normally you wouldn't use this script *and* systemd.
This script is something you'd use *instead* of creating a systemd unit.

If you're going to use a shell script to set up the PATH and other
environment variables and chain-load the service, but manage it all with
systemd, then the script would look something like this:

#!/bin/sh
set -a
PATH=/whatever/you/need
SOME_OTHER_VAR=stuff
exec serve -s /path/to/your/service

Even this is still considered less than optimal, but it does simplify
maintenance.  If you need to adjust the service's environment frequently,
you can edit the shell script more easily than you can edit the unit
file.  So, using this hybrid approach isn't the worst thing you could do.

Now, in terms of setting up the unit file -- assuming you want a
system-wide service rather than a --user service, I'd go in one of two
directions, depending on whether you want to run it as yourself, or as
a dedicated user.

If you're going to run it as yourself, albeit in a system-wide unit,
I'd put it in your $HOME/bin/ directory.  That's where it makes sense
to put scripts that you've written that only you use.

If you're going to set up a dedicated user account to run it, then I'd
put the script in /usr/local/bin or /usr/local/sbin.  (But realistically,
the hybrid approach with a systemd unit *and* a script doesn't really
fit with the dedicated user.)

For writing a unit file, there's a basic tutorial at
<https://wiki.debian.org/systemd/Services>.

I don't know how your service works (or Node.js, for that matter),
so I'm not sure if you want a "simple" service, or a "forking" service.
Let's assume "simple" at first.  This is appropriate if the service
is a single process that runs in the foreground and doesn't create
any child processes.

You also need a name.  Let's call it coreyserver.  And let's say you're
going to run it as yourself, and that your username is corey.

Then this unit file might work:

[Unit]
Description=Corey Server
After=network.target

[Service]
Type=simple
Restart=always
RestartSec=5
User=corey
Group=corey
ExecStart=/home/corey/bin/coreyserver

[Install]
WantedBy=multi-user.target

Reply via email to