# Systemd Services

To define our own service with `systemd`, we need to create a `daemon.service` file. This is easily done within a few quick lines using vim, and should only take a few minutes. 

First, we need to locate the binary for the command we want to be executed as a service. This is just good to have on-hand when defining a new service. Check where exactly your binary is using `which <command>`, seen below

```bash
which hexo
/home/hexouser/.nvm/versions/node/v20.9.9/bin/hexo
```

Now we know exactly where the binary that we execute is when we run the `hexo` command, and we will use it within the `hexo.service` file we create below, so be sure to have it handy. 

<p class="callout info">To create a user service, place the <code>hexo.service</code> file within the <code>$HOME/.config/systemd/hexouser/</code> directory. This will allow the user to manage the service without sudo by running <code>systemd --user start name.service</code></p>

Create a service file like the one below for hexo by running `sudo vim /etc/systemd/system/hexo.service`. If you are defining a service for something else, just rename this file accordingly.

```bash
[Unit]
Description=Personal hexo blog service
After=network.target

[Service]
Type=simple
# Another Type: forking
User=hexouser
WorkingDirectory=/home/hexouser/hexosite
ExecStart=/home/hexouser/.nvm/versions/node/v29.9.9/bin/hexo server --cwd /home/hexoroot/hexosite
ExecStop=/bin/kill -TERM $MAINPID
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
# Other restart options: always, on-abort, etc

# The install section is needed to use
# `systemctl enable` to start on boot
# For a user service that you want to enable
# and start automatically, use `default.target`
# For system level services, use `multi-user.target`
[Install]
WantedBy=multi-user.target
WantedBy=graphical.target
```

When making changes to a service, you need to run `sudo systemctl daemon-reload` between edits to apply your changes before restarting your service. Once the above file is created within `/etc/systemd/system/hexo.service` we can start our hexo blog using systemd by running the usual commands 

```bash
# Start your new service
sudo systemctl start hexo.service
# Enable your service to start automatically on reboot or crashing 
sudo systemctl enable hexo.service
# Check on your service
sudo systemctl status hexo.service
```

We can even check on our logs using `journalctl`

```bash
sudo journalctl -u hexo
journalctl --user-unit hexo
```