Why does the command 'apt install php' try to install Apache?

Solution 1:

According to this answer on AskUbuntu: How to install php without Apache webserver?:

Ubuntu package details says php (php7.2) depends on libapache2-mod-php7.2 OR php7.2-fpm OR php7.2-cgi.

It seems to default to the first package, which itself depends on apache2. But if you install one of the latter first, and php afterwards, apache2 will not be installed.

If you're using nginx, you probably want:

sudo apt install php php7.2-fpm

Solution 2:

As an alternative to the approach used in this answer in which you tell APT which dependency you do want, you can also specify which you don't want. For example in Ubuntu 20.04 (the method is still valid in 18.04 for php7.2), to display the dependencies for the php7.3 package (irrelevant lines omitted):

$ apt show php7.3
Depends: libapache2-mod-php7.3 | php7.3-fpm | php7.3-cgi, php7.3-common

The | symbol means "or" and is telling you that the dependency can be satisfied by either libapache2-mod-php7.3, php7.3-fpm or php7.3-cgi.

If we go ahead and install the package, we can see that APT will choose the first dependency from the list (libapache2-mod-php7.3):

# apt install php7.3
The following NEW packages will be installed:
  apache2 apache2-bin apache2-data apache2-utils libapache2-mod-php7.3 libapr1 libaprutil1
  libaprutil1-dbd-sqlite3 libaprutil1-ldap libjansson4 liblua5.2-0 php-common php7.3
  php7.3-cli php7.3-common php7.3-json php7.3-opcache php7.3-readline ssl-cert
Do you want to continue? [Y/n] n
Abort.

If you're not happy with that, you can tell APT that you do not want that dependency by placing a hyphen after the name of the unwanted package. If you do so, then APT will instead choose the second dependency from the list (php7.3-fpm):

# apt install php7.3 libapache2-mod-php7.3-
The following NEW packages will be installed:
  php-common php7.3 php7.3-cli php7.3-common php7.3-fpm php7.3-json php7.3-opcache
  php7.3-readline
Do you want to continue? [Y/n] n
Abort.

This approach is useful if you know you don't want a particular dependency but are indifferent as to which of the alternatives is used. On the other hand, if you know you need a specific one, use the method in the other answer.