apache2.service failed after Ubuntu upgrade to 22.04

Apache helicopter flying through a desert.
Issue found. Neutralizing target.

After I upgraded my Ubuntu server from 20.04 to 22.04, the built-in Apache service stopped working. When I tried to start it again with:

service apache2 start

The following error appeared:

Job for apache2.service failed because the control process exited with error code.
See "systemctl status apache2.service" and "journalctl -xeu apache2.service" for details.

Let's look at how to resolve that, and then another issue that occurred right after related to old PHP modules.

Set missing Apache environment vars

I ran apache2 -S to get clarity on the issue:

AH00111: Config variable ${APACHE_RUN_DIR} is not defined
apache2: Syntax error on line 80 of /etc/apache2/apache2.conf: DefaultRuntimeDir must be a valid directory, absolute or relative to ServerRoot

It looks like we're missing at least one environment variable, so let's set them with:

source /etc/apache2/envvars

Remove PHP 7.4 modules

Then I ran apache2 -S again, and yet another problem occurred:

apache2: Syntax error on line 146 of /etc/apache2/apache2.conf: Syntax error on line 3 of /etc/apache2/mods-enabled/php7.4.load: Cannot load /usr/lib/apache2/modules/libphp7.4.so into server: /usr/lib/apache2/modules/libphp7.4.so: cannot open shared object file: No such file or directory

I know that PHP was upgraded from 7.4 to 8.1 during the Ubuntu upgrade, which you can confirm with php -v:

PHP 8.1.2-1ubuntu2.9 (cli) (built: Oct 19 2022 14:58:09) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.2, Copyright (c) Zend Technologies
    with Zend OPcache v8.1.2-1ubuntu2.9, Copyright (c), by Zend Technologies

Therefore, the PHP 7.4 modules in Apache no longer exist, which is why Apache now won't start.

Take a look at which modules you have:

ll /etc/apache2/mods-enabled/ | grep php
lrwxrwxrwx 1 www-data www-data   29 Aug 16  2021 php7.4.conf -> ../mods-available/php7.4.conf
lrwxrwxrwx 1 www-data www-data   29 Aug 16  2021 php7.4.load -> ../mods-available/php7.4.load

Let's remove both the symlinks and the module files:

rm /etc/apache2/mods-enabled/php7.4*
rm /etc/apache2/mods-available/php7.4*

Include PHP 8.1 modules

Let's confirm that you have the PHP 8.1 modules:

ll /etc/apache2/mods-available/ | grep php
-rw-r--r-- 1 www-data www-data   855 Oct 19 14:58 php8.1.conf
-rw-r--r-- 1 www-data www-data   101 Oct 19 14:58 php8.1.load

We can now enable those:

cd /etc/apache2/mods-enabled
ln -s ../mods-available/php8.1.conf php8.1.conf
ln -s ../mods-available/php8.1.load php8.1.load

If you did this as root, let's update the permissions accordingly, too:

chown -h www-data:www-data php8.1*

Start Apache

That was the last problem and we can start Apache back up:

service apache2 start

Let me know if you run into a different issue by leaving a comment below.

Featured image by Andre Klimke.