Using systemd for development servers
As enjoyable as it is to launch your development servers by hand, it takes time. And if you switch between projects several times per day that time accumulates. That is especially true if you need to launch multiple servers for each project, for example background workers.
You’re probably familiar with systemd already as it’s the default system for managing system-wide processes. However, not many are aware of how easily it can also be used to manage user processes.
Just create a configuration such as myblog.service
and leave it in
~/.config/systemd/user
. The following snippet is a systemd configuration
for a jekyll dev server.
[Unit]
Description=Jekyll Development server for myblog.com
After=network.target
[Service]
WorkingDirectory=/home/sam/pj/myblog/myblog-jekyll
Environment="PATH=/home/sam/.gem/ruby/2.7.0/bin:/usr/bin"
ExecStart=/home/sam/.gem/ruby/2.7.0/bin/bundle exec jekyll serve --port 4000
ExecStop=kill -2 $MAINPID
Every time you change or add a configuration file you’ll have to trigger daemon-reload
.
After that, you can start your user service.
systemctl --user daemon-reload
systemctl --user start myblog
systemctl --user status myblog
As you can see, you need to pass the --user
flag. And this works without
sudo privileges, which is amazing.
Additionally, I allow dev servers that are not resource-hungry to run in the background continuously and start with the system.
For that, add a WantedBy
line in the Install
section of your service’s configuration
and enable your service.
[Install]
WantedBy=default.target
systemctl --user enable myblog
View the logs of your service.
journalctl --user -u myblog