How to uninstall or remove apache2 using command line?

Installing apache2 is quite simple and easy. In some cases, we may need to uninstall or remove apache2 from the system. It could be we want to use a different web server and remove apache2 permanently.

The use case can be, we have an existing apache2 but we want to remove it completely and install a fresh one. Anyway, if we want to remove or install apache2 from the system following are the steps:

Stop apache2:

First of all, we need to stop apache2 if it is already running. Try the following command to stop apache2.

// Stop apache2
$ sudo service apache2 stop
or
$ sudo systemctl stop apache2.service

Cleanup apache2 packages:

Now we to remove and cleanup all the apache2 packages from the system using the following command.

// Cleanup apache2 packages
$ sudo apt-get purge apache2 apache2-utils apache2.2-bin apache2-common
//or
$ sudo apt-get purge apache2 apache2-utils apache2-bin apache2.2-common

Remove other dependencies:

Remove other dependencies those are not in use.

// Remove other dependencies
$ sudo apt-get autoremove

Confirm apache2 removal:

We need to now check the apache2 has been removed or not using the following commands:

// This command should return a blank line
$ which apache2

// This command should return apache2: unrecognized service
$ sudo service apache2 start

Remove apache2 directory if needed:

When you run this command whereis apache2 if you get a response like below:

apache2: /etc/apache2 remove the directory and existing configuration files.

Then we need to remove the apache2 directory from /etc directory using the following command:

// Remove apache2 directory
$ sudo rm -rf /etc/apache2
Reference: