How to create systemd unit that depends on a website being up?
I'm going to write some systemd services. All of these can only be run if a certain website is up. I thought I could create a ~/.config/systemd/user/website.service
this:
[Unit]
Description=Confirm that example is up
Wants=network-online.target
After=network-online.target nss-lookup.target
[Service]
ExecStart=curl --head example.com
And then I can make my actual units have Requires=website.service
.
When I run systemctl --user start website
, it just exits. When I check systemctl --user status website
I see the header in the logs. But the status just says "inactive", not success or fail (based on exit code of fail).
When I tell systemd to run my other units, it should first run website.service
, and only if it succeeds should the target units run. Otherwise they should fail. How do I accomplish this?
1 answer
To make your example work, you should add Type=oneshot
and RemainAfterExit=true
to the [Service]
section.
This way the unit won't be considered active until the curl has actually succeeded, and either won't go inactive afterwards.
However, this is somewhat unorthodox way of going about it. One would expect website.service
to really manage the service process, and not be just a proxy for it (using curl in this case).
Instead you could just add the unit actually managing the server process as a dependency to your other units. E.g. on Ubuntu your website might be running on Apache:
[Unit]
Description=A thing requiring the website
Requisite=apache2.service
After=apache2.service
[Service]
...
Requisite makes starting the unit simply fail if Apache isn't running. It won't try to start it (as unwittingly starting web services can lead to security issues).
2 comment threads