Boot issue with systemd and NGINX

I ran into a problem with NGINX failing to start on boot/reboot on my Debian 8 (Jessie) server. After reviewing what seemed like a hundred sites to try to find a fix, I stumbled across one solution that worked, but was incredibly inelegant. This was to add:

RestartSec=30s
Restart=on-failure

to nginx.service in the [Service] section using the override.conf. It worked but didn't fix the underlying problem.

A quick look using `journalctl -u nginx` showed that the service was failing because the IPv6 address hadn't been assigned to the network adaptor yet. This caused nginx to fail because it couldn't bind to the IPv6 port. Here are the log lines:

May 08 10:59:38 mail1 nginx[3446]: nginx: [emerg] bind() to [2600:3c01::f03c:91ff:fedb:579b]:80 failed (99: Cannot assign requested address)
May 08 10:59:38 mail1 nginx[3446]: nginx: configuration file /etc/nginx/nginx.conf test failed

A simple, and much more elegant solution, is to change `After=network.target` to `After=network-online.target` in the [Unit] section of the nginx.service file. Apparently, network.target only checks for the start of the network service whereas network-online.target actually ensures the network is available before attempting to start nginx.

Steps to fix:

systemctl edit nginx

This creates `/etc/systemd/system/nginx.service.d/override.conf`.

Place this snippet in override.conf.

[Unit]
After=network-online.target

And you’re done.