The previous (sadly, now deleted) answer by a helpful user whose nick slipped my mind already was almost correct.
It suggested to amend the /lib/systemd/system/apache2.service
file to make it depend on network-online.target
instead of the default network.target
or, better, to add a second file to /lib/systemd/system
called my-apache2.service
with this modification. As per the documentation this is the correct way to make sure that a service only starts when the network is really up.
While this works the problem here is that the contents of /lib
are not supposed to be edited and /etc/systemd/system
should be used for this purpose instead. (Yes, this answer I linked to deals with systems other than Ubuntu, but reading man 7 file-hierarchy
and man 5 systemd.unit
on Ubuntu shows the same thing).
The second problem is that, from my experience, trying to run Apache2 twice leads to problems.
To remedy both problems my answer previously recommended the creation of a conflicting service in /etc/systemd/system
. However, this was overly complicated and failed to solve some of the above problems, namely it was not future proof: changes to the original .service
file made by upstream authors would not automatically be incorporated into our new .service
file.
The correct solution is to create a drop-in file that adds a new After
dependency to the original apache2.service
, as documented by man 5 systemd.unit
. To do so one needs to enter the following command:
# systemctl edit apache2.service
(which is documented in man 1 systemctl
)
...and when the editor opens one needs to enter the following contents between the ### Anything between here and the comment below
... and ### Lines below this comment
... lines:
[Unit]
After=network-online.target
And save the new file.
Note that as per man 5 systemd.unit
this will not replace the original After dependencies of the service; rather, this will add a new dependency to the ones that are already present.
For reference, here are the original contents of /lib/systemd/system/apache2.service
:
[Unit]
Description=The Apache HTTP Server
After=network.target remote-fs.target nss-lookup.target
Documentation=https://httpd.apache.org/docs/2.4/
[Service]
Type=forking
Environment=APACHE_STARTED_BY_SYSTEMD=true
ExecStart=/usr/sbin/apachectl start
ExecStop=/usr/sbin/apachectl graceful-stop
ExecReload=/usr/sbin/apachectl graceful
KillMode=mixed
PrivateTmp=true
Restart=on-abort
[Install]
WantedBy=multi-user.target
From now on Apache2 should no longer fail to start on system boot.