Trying to restart apache from terminal using the following command:
sudo service apache2 restart
When executing that command, I’m getting below error:
Job for apache2.service failed. See "systemctl status apache2.service" and "journalctl -xe" for details.
On excuting «systemctl status apache2.service» I get this output:
apache2.service - (null)
Loaded: loaded (/etc/init.d/apache2)
Active: failed (Result: exit-code) since Sat 2015-05-30 02:22:41 IST; 12s ago
Docs: man:systemd-sysv-generator(8)
Process: 4866 ExecStart=/etc/init.d/apache2 start (code=exited, status=1/FAILURE)
Apache error.log
:
AH00489: Apache/2.4.12 (Unix) configured -- resuming normal operations
AH00094: Command line: '/usr/local/apache2/bin/httpd'
asked May 29, 2015 at 20:48
Gautam SavaliyaGautam Savaliya
2,2413 gold badges13 silver badges10 bronze badges
7
There is some syntax error in the file apache2.conf
.
In a terminal, type:
cd /etc/apache2
Then:
apache2ctl configtest
It will show you where is the error in the apache2.conf
file to correct.
Eliah Kagan
115k53 gold badges311 silver badges484 bronze badges
answered Aug 1, 2016 at 18:31
9
Maybe this will help to find the cause:
journalctl | tail
In my case it was a mistake in the configuration file:
AH00526: Syntax error on line 5 of /etc/apache2/sites-enabled/mydomain-wsf.lan.conf
answered Aug 18, 2015 at 10:16
ArekArek
9766 silver badges7 bronze badges
5
The problem is because some configuration files are deleted, you have to reinstall it.
REINSTALL APACHE2:
To replace configuration files that have been deleted, without purging the package, you can do:
sudo apt-get -o DPkg::Options::="--force-confmiss" --reinstall install apache2
To fully remove the apache2 config files, you should:
sudo apt-get purge apache2
which will then let you reinstall it in the usual way with:
sudo apt-get install apache2
Purge is required to remove all the config files — if you delete the config files but only remove the package, then this is remembered & missing config files are not reinstalled by default.
Then REINSTALL PHP5:
apt-get purge libapache2-mod-php5 php5 &&
apt-get install libapache2-mod-php5 php5
Parto
14.8k24 gold badges85 silver badges113 bronze badges
answered Mar 15, 2016 at 10:06
2
Problem:
Job for apache2.service failed because the control process exited with error code. See "systemctl status apache2.service" and "journalctl -xe" for details.
Solution:
-
To fully remove the apache2 config files, you should:
1)
sudo apt-get purge apache2
-
which will then let you reinstall it in the usual way with:
2)
sudo apt-get install apache2
==> It Works fine…
thanks….
Videonauth
32.6k16 gold badges102 silver badges119 bronze badges
answered Dec 27, 2016 at 7:12
I got the same error after removing a virtual host. The problem was the lingering SSL conf file associated with that host located in /etc/apache2/sites-enabled
. The SSL was through Let’s Encrypt so the code for me to remove was:
sudo rm yourdomain.com-le-ssl.conf
answered Mar 1, 2017 at 19:47
0
you most likely have a syntax error. for me it was in my ‘sites-enabled’ folder.
i mis-spelled ‘ServerAlias’ to ‘ServerAlisa’.
answered Sep 15, 2017 at 12:12
1
I got the Same errors While working with .htaccess
I just put this command
<Directory /var/www/html>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
in /etc/apache2/sites-enabled/000-default.conf
this folder
after adding this i have getting the error
then i delete these peace of command from the file and my error has resolved.
answered Jul 26, 2017 at 5:48
This is mostly a configuration error. I just now had an old site enabled on apache, what caused this error. So I had to disable it before reloading apache.
sudo a2dissite <my-site>
sudo service apache2 reload
Problem solved
answered Aug 20, 2016 at 6:15
Thank you for your help! I was able to install correctly with Solution:
To fully remove the apache2 config files, you should:
-
sudo apt-get purge apache2
which will then let you reinstall it in the usual way with: -
sudo apt-get install apache 2
It now works fine.
muru
189k52 gold badges460 silver badges711 bronze badges
answered Jan 16, 2017 at 1:41
I think the problem is that you have some site enabled but you deleted its configuration file. Try disabling the site with
sudo a2dissite «name»
and then restart apache server. At least this was the problem for me and this action solved it.
answered May 16, 2017 at 14:56
In my case, the error started to appear after doing apt upgrade
. After playing a lot I went to following directories to see what I can disable.
- /etc/apache2/mods-enabled —
a2dismod
(to turn back ona2enconf
) - /etc/apache2/conf-enabled —
a2disconf
(to turn back ona2enconf
)
In my case, I had to those MODS enabled.
It seems that apt-upgrade
must have removed/broken php7.2 because as soon as I disabled it and restarted everything worked. Of course, in anyone else’s case, it may be something different. When Apache crashes it may be bad config or bad mod. You have to pick your battles.
answered Sep 8, 2019 at 11:20
MadBoyMadBoy
5615 silver badges11 bronze badges
For what it may be relevant at this stage, but today I came across the same problem and it turned out to be an issue with the certificate file.
So eventually the config was all ok, but in uploading the new .crt content I did in the wrong file, meaning there were no more matching for a particular site and the whole server was refusing to start.
No indication of incorrect SSL certificate in the log or anywhere else, which took me a while to figure out.
answered Mar 7, 2020 at 9:14
Andrea MoroAndrea Moro
4211 gold badge5 silver badges15 bronze badges
Содержание
- How to fix common problems with Apache2
- Make sure the service is running
- Check your server configuration
- Check Logs
- Check other services
- Устранение общих ошибок Apache
- Команды systemctl для Apache
- Команды journalctl для Apache
- Устранение неполадок с помощью apachectl
- Логи Apache
- Заключение
How to fix common problems with Apache2
Problems with loading a website are often blamed on the Internet connection, but even the most perfectly set up network cannot help if there is no service to reply at your destination. One of the most popular HTTP servers used for this task is Apache2. Much of Apache’s popularity can be attributed to its easy installation and use, but never the less it is possible to run into problems with even the easiest of the software. If you’ve encountered an issue loading your web page, follow these simple troubleshooting methods outlined in this guide to attempt to get your web server back up and working again.
Make sure the service is running
The first step to take in troubleshooting any service is to check that the service is running and able to function. A straightforward approach is to simply restart the service. On Ubuntu and Debian servers use the following command.
In CentOS and other Red Hat environments Apache2 service goes by the name ‘httpd’, so use this command instead.
Depending on your choice of distribution the output from the restart command will vary. Subjectively Ubuntu usually gives the most helpful reply as shown below.
CentOS and Debian probably do not say anything as long as the restart didn’t fail.
If your system wasn’t able to restart Apache2 you most likely got some form of an error message. In case you got a reply resembling either one of the output examples below, the service is most likely not properly installed on your system or some files are missing.
Should you see these type of errors, try installing the service again. On servers running Debian or Ubuntu use the following command.
And on CentOS install httpd instead with the next command.
Once you are sure the web server is fully installed go ahead and restart the service again with the same command you used before.
If you got a different error message, try to get more information on what kind of state your web service is in. Use one of the following commands applicable to your system.
The output from the status check will tell at least whether the service is running or stopped. Debian and CentOS systems usually show more detailed report including service up time and a couple of log lines. Below is an example of a Debian status display, one on CentOS would be nearly identical. Ubuntu does not have this type of output by default.
The important part here is on the third line, active and running means the process should be working, if instead it shows active and stopped or failed, the process has most likely crashed.
Next check the processes by their name for either apache2 or httpd.
For every mention of the searched keyword grep will print out a line the keyword was found on, this includes the search process itself so you will see at least the grep command. If there are more than one line of output, all but the last are processes related to your web service. An example below displays apache2 processes running on Ubuntu.
Since the service restart command didn’t work earlier, any processes grep might list have probably stopped functioning and need to be closed before the service can start again. On Debian and Ubuntu systems stop all apache2 processes using this command.
On CentOS servers not only is the web service called something else but also the kill command functions little differently, use the following instead for the same result.
After the kill command, you can run the process check again just to confirm that there are no more zombies left. Then try to restart the service using these same commands as at the beginning of this guide.
This should get the web service running provided that it has not been misconfigured.
Check your server configuration
When starting the service fails giving errors referring to files located in either /etc/apache2 or /etc/httpd/, the system had trouble reading the service configuration files. Apache2 comes with some handy tools for file integrity and syntax checks that can help in locating any typing mistakes or other irregularities in the configuration. With Debian and Ubuntu servers, check the config files by running the following command.
On CentOS machines just call httpd instead.
The output will show any problems found with the configuration file. Or if everything is in order, it simply prints out a confirmation like the one shown below.
Another troubleshooting option for the web service is to show parsed virtual host and run settings with commands for Debian/Ubuntu and CentOS respectively.
Below is an example of the command output from a CentOS system. Make sure the server and document roots point to the correct directories.
If your server uses a custom virtual host configuration, like when hosting multiple websites on one server, check that each virtual host file has the correct domain name and points to the correct root directory. On Debian and Ubuntu machines have a virtual host file by default and it is stored in /etc/apache2/sites-enabled/. Open the file for edit.
This file usually has some instructions on what each parameter means in the comments, which have been left out in the example below, but the important parts are ServerName and DocumentRoot as already mentioned.
CentOS and httpd do not have the same virtual host file set by default but instead uses the httpd service configuration to store the default settings. Check the configuration file with the command below.
Look for the same parameters ServerName and DocumentRoot, and make sure they are correctly set.
If you made any changes to the configuration files, the service needs to be reloaded for the changes to take an effect. Restarting the service does the job, but if you wish to avoid downtime on your web server use reload instead with one of the following commands.
Check Logs
When everything on the service side is working as expected and you cannot find a fault, but the website just still won’t load, it’s always a good time to dig through logs. Apache2 keeps two sets of logs, access and error. You can find the logs stored at /var/log/apache2/ or /var/log/httpd depending on your choice of Linux distribution. You can list all files in your web server’s log directory using the commands below.
The log lists will differ slightly as different systems name the logs a little differently. Ubuntu and Debian servers store the current uptime logs to access.log or error.log, previous logs are marked with a running number, 1 being the latest, and older logs than that are also compressed. On CentOS and other Red Hat variants, the logs are named access_log and error_log, older logs have their name appended with the date the log was written on e.g. access_log-20150108.
An easy way to start reading the logs, when you don’t necessarily know what you are looking for, is to use the filtering app ‘grep’. Search for any errors using one of the commands below which corresponds with your system’s web application name.
Ubuntu and Debian users might also need to check through the compressed log files. This can be done using ‘zgrep’ instead, but due to its limitations, you can only search one log at the time, for example using this following command.
Not all errors logged by your web service necessarily mean there is something wrong with your server, but keep an eye out for any repeating problems like missing files in the example error below.
You may also wish to enable more verbose logging if searching for errors is not yielding any results. The log output amount is controlled by a parameter called ‘LogLevel’ in the configuration file. On Debian and Ubuntu systems, open your configuration file with the following command.
With CentOS and other Red Hat based server use the command here instead.
Find the LogLevel parameter and change it from the default ‘warn’ value to ‘debug’ instead, then save the file and exit. Again for any changes to be applied, the service needs to be reloaded. You can do this with one of the following commands appropriate for your system.
To generate some new entries using the new log levels, try to access your website again a couple of times even if it doesn’t work. The more verbose logs should help with narrowing down any underlying issues.
Check other services
If your website still won’t load after all the troubleshooting with Apache, check other related services on your cloud server such as databases, firewall and network connection, which also have their own troubleshooting instructions.
Do not hesitate to contact our support team. Remember to include any relevant information you may have discovered while troubleshooting, as every bit of detail, will be useful in further investigations.
Источник
Устранение общих ошибок Apache
Эта серия мануалов поможет вам предотвратить или устранить самые распространенные ошибки, которые возникают при работе с веб-сервером Apache.
Каждый последующий мануал в этой серии включает описание распространенных ошибок Apache, связанных с конфигурацией, сетью, файловой системой или привилегиями. Мы начнем с обзора команд и логов, которые вы можете использовать для устранения неполадок Apache. В последующих руководствах мы подробно рассмотрим конкретные ошибки.
Есть три основные команды и несколько общих логов, которые вы можете использовать, чтобы начать устранение ошибок Apache. По сути здесь вы найдете стандартную стратегию поиска ошибок и их причин: обычно эти команды используются в указанном здесь порядке, после чего можно изучить логи на предмет конкретных диагностических данных.
Команды, которые необходимы для устранения неполадок Apache в большинстве дистрибутивов Linux:
- systemctl – используется для управления сервисами Linux и взаимодействия с ними через менеджер сервисов systemd.
- journalctl – используется для запроса и просмотра логов, созданных systemd.
- apachectl – при устранении неполадок эта команда используется для проверки конфигурации Apache.
Далее мы подробно опишем эти команды, способы их использования и расположение логов Apache, в которых можно найти дополнительную информацию об ошибках.
Примечание: В системах Debian и Ubuntu сервис и процесс Apache называется apache2, а в CentOS, Fedora и других системах RedHat – httpd. Имя сервиса и процесса – это единственное отличие команд запуска, остановки и проверки состояния Apache в разных системах. Логи journalctl также должны работать одинаково в любой системе Linux, которая использует systemd для управления Apache. При работе с этим мануалом вы должны использовать правильное имя сервиса в зависимости от вашего дистрибутива Linux.
Команды systemctl для Apache
Чтобы устранить распространенные ошибки Apache с помощью менеджера сервисов systemd, первым делом вам необходимо проверить состояние процессов Apache в вашей системе. Следующие команды systemctl помогут вам узнать больше о состоянии процессов Apache.
В Ubuntu и Debian используйте:
sudo systemctl status apache2.service -l —no-pager
Флаг -l отображает полный вывод без сокращения. Флаг –no-pager направляет вывод непосредственно на ваш терминал. Вы должны получить такой результат:
apache2.service — The Apache HTTP Server
Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
Drop-In: /lib/systemd/system/apache2.service.d
└─apache2-systemd.conf
Active: active (running) since Mon 2020-07-13 14:43:35 UTC; 1 day 4h ago
Process: 929 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/SUCCESS)
Main PID: 1346 (apache2)
Tasks: 55 (limit: 4702)
CGroup: /system.slice/apache2.service
├─1346 /usr/sbin/apache2 -k start
. . .
Чтобы изучить процесс веб-сервера в CentOS и Fedora, используйте:
sudo systemctl status httpd.service -l —no-pager
Вы получите такой результат:
httpd.service — The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
Active: active (running) since Tue 2020-07-14 19:46:52 UTC; 3s ago
Docs: man:httpd.service(8)
Main PID: 21217 (httpd)
Status: «Started, listening on: port 80»
Tasks: 213 (limit: 2881)
Memory: 16.6M
CGroup: /system.slice/httpd.service
├─21217 /usr/sbin/httpd -DFOREGROUND
. . .
Jul 14 19:46:52 localhost.localdomain httpd[21217]: Server configured, listening on: port 80
Независимо от дистрибутива вы должны обратить внимание на строку Active в выводе. Если ваш сервер Apache не отображается как active (running), хотя он должен работать, возможно, произошла ошибка и прервала его работу. Как правило, при возникновении ошибок в выводе будет строка failed:
Active: failed (Result: exit-code) since Tue 2020-07-14 20:01:29 UTC; 1s ago
Если проблема заключается в процессе или конфигурации Apache, вы можете устранить ее с помощью команды journalctl.
Команды journalctl для Apache
Чтобы проверить логи systemd для Apache, вы можете использовать команду journalctl. Логи systemd для Apache обычно содержат данные о проблемах с запуском или управлением процессом Apache.
Эти логи отделены от логов запросов и ошибок Apache. Команда journalctl отображает логи systemd, которые описывают сам сервис Apache (от его запуска до завершения работы, включая все ошибки процесса, которые могут возникнуть на этом пути).
В системах Ubuntu и Debian для проверки логов используйте следующую команду:
sudo journalctl -u apache2.service —since today —no-pager
Флаг –since today ограничивает вывод команды записями лога, начиная с 00:00:00 текущего дня. Использование этой опции поможет ограничить объем записей лога, которые вам необходимо изучить для выявления ошибок. Вы должны получить следующий результат:
Jul 14 20:12:14 ubuntu2004 systemd[1]: Starting The Apache HTTP Server.
Jul 14 20:12:14 ubuntu2004 systemd[1]: Started The Apache HTTP Server.
Если вы используете систему на базе CentOS или Fedora, введите эту версию команды:
sudo journalctl -u httpd.service —since today —no-pager
Вы получите такой результат:
Jul 14 20:13:09 centos8 systemd[1]: Starting The Apache HTTP Server.
. . .
Jul 14 20:13:10 centos8 httpd[21591]: Server configured, listening on: port 80
В случае ошибки в выводе будет строка, приведенная ниже (имя хоста будет отличаться в зависимости от дистрибутива Linux):
Jul 14 20:13:37 yourhostname systemd[1]: Failed to start The Apache HTTP Server.
Если в ваших логах Apache есть подобные ошибки, то следующее, что нужно сделать для устранения возможных проблем – это исследовать конфигурации Apache с помощью инструмента командной строки apachectl.
Устранение неполадок с помощью apachectl
Большинство дистрибутивов Linux включают утилиту apachectl в установку Apache по умолчанию. apachectl – бесценный инструмент, помогающий обнаруживать и диагностировать проблемы конфигурации Apache.
Проверьте конфигурацию Apache с помощью команды apachectl configtest. Инструмент проанализирует ваши файлы Apache и обнаружит все ошибки или недостающие настройки перед попыткой запуска сервера.
Команда одинакова для дистрибутивов Ubuntu, Debian, CentOS и Fedora:
sudo apachectl configtest
Если конфигурация Apache не содержит ошибок, вы получите такой результат:
В зависимости от вашего дистрибутива Linux в выводе могут быть и другие строки, но самая важная строка – это та, в которой говорится, что с синтаксисом все ок.
Если в вашей конфигурации Apache есть ошибка (например, директива ссылается на деактивированный модуль) или опечатка, apachectl обнаружит ее и попытается уведомить вас о проблеме.
Например, попытка использовать в директиве отключенный модуль Apache приведет к появлению следующих сообщений apachectl:
AH00526: Syntax error on line 232 of /etc/apache2/apache2.conf:
Invalid command ‘SSLEngine’, perhaps misspelled or defined by a module not included in the server configuration
Action ‘configtest’ failed.
The Apache error log may have more information.
В этом примере модуль ssl не включен, поэтому при проверке конфигурации директива SSLEngine выдает ошибку. Последняя строка также указывает, что в логе ошибок Apache может содержаться дополнительная информация, и это следующее место для поиска подробной отладочной информации.
Логи Apache
Логи Apache – очень полезный ресурс для устранения неполадок. Как правило, каждая ошибка, возникающая в браузере или другом HTTP-клиенте, создает соответствующую запись в логах Apache. Иногда Apache также выводит в свои логи ошибки, связанные с конфигурацией, встроенными модулями и другой отладочной информацией.
Чтобы проверить ошибки при устранении неполадок Apache на сервере Fedora, CentOS или RedHat, изучите файл /var/log/httpd/error_log.
Если вы устраняете неполадки в системе Debian или Ubuntu, проверьте /var/log/apache2/error.log с помощью инструмента tail или less. Например, чтобы просмотреть последние две строки лога ошибок с помощью tail, выполните следующую команду:
sudo tail -n 2 /var/log/apache2/error.log
Замените количество строк, которые вы хотите изучить. Укажите количество строк вместо числа 2 в команде.
В системе CentOS или Fedora файл журнала для проверки – /var/log/httpd/error_log.
Ниже мы приводим пример пример ошибки (ее текст не зависит от дистрибутива Linux):
[Wed Jul 15 01:34:12.093005 2020] [proxy:error] [pid 13949:tid 140150453516032] (13)Permission denied: AH00957: HTTP: attempt to connect to 127.0.0.1:9090 (127.0.0.1) failed
[Wed Jul 15 01:34:12.093078 2020] [proxy_http:error] [pid 13949:tid 140150453516032] [client 127.0.0.1:42480] AH01114: HTTP: failed to make connection to backend: 127.0.0.1
Эти две строки представляют собой отдельные сообщения об ошибках. Обе они ссылаются на модуль, вызвавший ошибку (proxy в первой строке, proxy_http во второй), и содержат код ошибки, индивидуальный для модуля. Первый, AH00957, указывает на то, что сервер Apache пытался подключиться к бэкенд-серверу (в данном случае к 127.0.0.1 по порту 9090) с помощью модуля proxy, но не смог этого сделать.
Вторая ошибка исходит из первой: AH01114 – это ошибка модуля proxy_http, которая также указывает на то, что Apache не смог подключиться к бэкенд-серверу для выполнения HTTP-запроса.
Эти строки мы привели просто для примера. Если вы диагностируете ошибки на своем сервере Apache, скорее всего, вы найдете совсем другие строки с ошибками в ваших логах. Независимо от дистрибутива Linux, строки ошибок в логах всегда содержат соответствующий модуль Apache и код ошибки, а также текстовое описание ошибки.
Как только вы поймете, что могло вызвать вызывать проблему на вашем сервере Apache, вы можете продолжить исследование и устранение неполадок. Код ошибки и текстовое описание особенно полезны, поскольку дают конкретные указания, которые можно использовать для сужения диапазона возможных причин возникновения ошибки.
Заключение
Устранение ошибок Apache может включать как диагностику ошибок сервиса, так и обнаружение неверно настроенных параметров модулей. В этом вводном руководстве по диагностике Apache мы посмотрели, как использовать ряд утилит, чтобы сузить круг возможных причин появления ошибок. Обычно эти утилиты нужно использовать в том же порядке, в каком они описаны тут (но вы всегда можете пропустить некоторые действия или начать сразу с изучения логов, если у вас есть общее представление о том, в чем может быть проблема).
Однако чаще всего полезно следовать общей схеме устранения неполадок и использовать эти инструменты в описанном порядке. Начните с systemctl, чтобы проверить состояние сервера Apache. Если вам нужна дополнительная информация, изучите логи systemd для Apache с помощью команды journalctl. Если после проверки journalctl проблема все еще не ясна, проверьте конфигурации Apache с помощью команды apachectl configtest. Для более глубокого изучения неполадок проверьте логи Apache, обычно они указывают на конкретную ошибку (предоставляя полезные для диагностики данные и коды ошибок).
Источник
Problems with loading a website are often blamed on the Internet connection, but even the most perfectly set up network cannot help if there is no service to reply at your destination. One of the most popular HTTP servers used for this task is Apache2. Much of Apache’s popularity can be attributed to its easy installation and use, but never the less it is possible to run into problems with even the easiest of the software. If you’ve encountered an issue loading your web page, follow these simple troubleshooting methods outlined in this guide to attempt to get your web server back up and working again.
Try UpCloud for free! Deploy a server in just 45 seconds
Make sure the service is running
The first step to take in troubleshooting any service is to check that the service is running and able to function. A straightforward approach is to simply restart the service. On Ubuntu and Debian servers use the following command.
sudo systemctl restart apache2
In CentOS and other Red Hat environments Apache2 service goes by the name ‘httpd’, so use this command instead.
sudo systemctl restart httpd
Depending on your choice of distribution the output from the restart command will vary. Subjectively Ubuntu usually gives the most helpful reply as shown below.
* Restarting web server apache2 [ OK ]
CentOS and Debian probably do not say anything as long as the restart didn’t fail.
If your system wasn’t able to restart Apache2 you most likely got some form of an error message. In case you got a reply resembling either one of the output examples below, the service is most likely not properly installed on your system or some files are missing.
apache2: unrecognized service
Failed to restart apache2.service: Unit apache.service failed to load: No such file or directory.
Should you see these type of errors, try installing the service again. On servers running Debian or Ubuntu use the following command.
sudo apt-get install apache2
And on CentOS install httpd instead with the next command.
sudo yum install httpd
Once you are sure the web server is fully installed go ahead and restart the service again with the same command you used before.
If you got a different error message, try to get more information on what kind of state your web service is in. Use one of the following commands applicable to your system.
sudo systemctl status apache2
sudo systemctl status httpd
The output from the status check will tell at least whether the service is running or stopped. Debian and CentOS systems usually show more detailed report including service up time and a couple of log lines. Below is an example of a Debian status display, one on CentOS would be nearly identical. Ubuntu does not have this type of output by default.
● apache2.service - LSB: Apache2 web server Loaded: loaded (/etc/init.d/apache2) Active: active (running) since Fri 2015-07-31 10:44:26 EEST; 2h 14min ago Process: 9704 ExecStop=/etc/init.d/apache2 stop (code=exited, status=0/SUCCESS) Process: 9711 ExecStart=/etc/init.d/apache2 start (code=exited, status=0/SUCCESS) CGroup: /system.slice/apache2.service ├─9726 /usr/sbin/apache2 -k start ├─9730 /usr/sbin/apache2 -k start ├─9731 /usr/sbin/apache2 -k start ├─9732 /usr/sbin/apache2 -k start ├─9733 /usr/sbin/apache2 -k start ├─9734 /usr/sbin/apache2 -k start └─9747 /usr/sbin/apache2 -k start Jul 31 10:44:26 debian.example.com apache2[9711]: Starting web server: apache2.
The important part here is on the third line, active and running means the process should be working, if instead it shows active and stopped or failed, the process has most likely crashed.
Next check the processes by their name for either apache2 or httpd.
sudo ps aux | grep -E 'apache2|httpd'
For every mention of the searched keyword grep will print out a line the keyword was found on, this includes the search process itself so you will see at least the grep command. If there are more than one line of output, all but the last are processes related to your web service. An example below displays apache2 processes running on Ubuntu.
root 1457 0.0 1.5 321908 16132 ? Ss Jul30 0:02 /usr/sbin/apache2 -k start www-data 1461 0.0 2.8 326532 29172 ? S Jul30 0:00 /usr/sbin/apache2 -k start www-data 1462 0.0 3.1 327480 32364 ? S Jul30 0:00 /usr/sbin/apache2 -k start www-data 1463 0.0 2.9 326688 30260 ? S Jul30 0:00 /usr/sbin/apache2 -k start www-data 1464 0.0 3.1 326496 32148 ? S Jul30 0:00 /usr/sbin/apache2 -k start www-data 1465 0.0 2.7 326816 28040 ? S Jul30 0:00 /usr/sbin/apache2 -k start www-data 1841 0.0 2.0 323132 21044 ? S Jul30 0:00 /usr/sbin/apache2 -k start www-data 1871 0.0 2.2 323396 23280 ? S Jul30 0:00 /usr/sbin/apache2 -k start user 11669 0.0 0.0 11744 928 pts/0 S+ 15:32 0:00 grep --color=auto -E apache2|httpd
Since the service restart command didn’t work earlier, any processes grep might list have probably stopped functioning and need to be closed before the service can start again. On Debian and Ubuntu systems stop all apache2 processes using this command.
sudo killall apache2
On CentOS servers not only is the web service called something else but also the kill command functions little differently, use the following instead for the same result.
sudo kill -a httpd
After the kill command, you can run the process check again just to confirm that there are no more zombies left. Then try to restart the service using these same commands as at the beginning of this guide.
sudo systemctl status apache2
sudo systemctl status httpd
This should get the web service running provided that it has not been misconfigured.
Check your server configuration
When starting the service fails giving errors referring to files located in either /etc/apache2 or /etc/httpd/, the system had trouble reading the service configuration files. Apache2 comes with some handy tools for file integrity and syntax checks that can help in locating any typing mistakes or other irregularities in the configuration. With Debian and Ubuntu servers, check the config files by running the following command.
sudo apache2ctl -t
On CentOS machines just call httpd instead.
sudo httpd -t
The output will show any problems found with the configuration file. Or if everything is in order, it simply prints out a confirmation like the one shown below.
Syntax OK
Another troubleshooting option for the web service is to show parsed virtual host and run settings with commands for Debian/Ubuntu and CentOS respectively.
sudo apache2ctl -S
sudo httpd -S
Below is an example of the command output from a CentOS system. Make sure the server and document roots point to the correct directories.
VirtualHost configuration: ServerRoot: "/etc/httpd" Main DocumentRoot: "/var/www/html" Main ErrorLog: "/etc/httpd/logs/error_log" Mutex proxy: using_defaults Mutex authn-socache: using_defaults Mutex default: dir="/run/httpd/" mechanism=default Mutex mpm-accept: using_defaults Mutex authdigest-opaque: using_defaults Mutex proxy-balancer-shm: using_defaults Mutex rewrite-map: using_defaults Mutex authdigest-client: using_defaults PidFile: "/run/httpd/httpd.pid" Define: DUMP_VHOSTS Define: DUMP_RUN_CFG User: name="apache" id=48 Group: name="apache" id=48
If your server uses a custom virtual host configuration, like when hosting multiple websites on one server, check that each virtual host file has the correct domain name and points to the correct root directory. On Debian and Ubuntu machines have a virtual host file by default and it is stored in /etc/apache2/sites-enabled/. Open the file for edit.
sudo nano /etc/apache2/sites-enabled/000-default.conf
This file usually has some instructions on what each parameter means in the comments, which have been left out in the example below, but the important parts are ServerName and DocumentRoot as already mentioned.
<VirtualHost *:80> ServerName www.example.com ServerAdmin [email protected] DocumentRoot /var/www/html #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined #Include conf-available/serve-cgi-bin.conf </VirtualHost>
CentOS and httpd do not have the same virtual host file set by default but instead uses the httpd service configuration to store the default settings. Check the configuration file with the command below.
sudo vi /etc/httpd/conf/httpd.conf
Look for the same parameters ServerName and DocumentRoot, and make sure they are correctly set.
If you made any changes to the configuration files, the service needs to be reloaded for the changes to take an effect. Restarting the service does the job, but if you wish to avoid downtime on your web server use reload instead with one of the following commands.
sudo systemctl reload apache2
sudo systemctl reload httpd
Check Logs
When everything on the service side is working as expected and you cannot find a fault, but the website just still won’t load, it’s always a good time to dig through logs. Apache2 keeps two sets of logs, access and error. You can find the logs stored at /var/log/apache2/ or /var/log/httpd depending on your choice of Linux distribution. You can list all files in your web server’s log directory using the commands below.
sudo ls /var/log/apache2/
sudo ls /var/log/httpd/
The log lists will differ slightly as different systems name the logs a little differently. Ubuntu and Debian servers store the current uptime logs to access.log or error.log, previous logs are marked with a running number, 1 being the latest, and older logs than that are also compressed. On CentOS and other Red Hat variants, the logs are named access_log and error_log, older logs have their name appended with the date the log was written on e.g. access_log-20150108.
An easy way to start reading the logs, when you don’t necessarily know what you are looking for, is to use the filtering app ‘grep’. Search for any errors using one of the commands below which corresponds with your system’s web application name.
sudo grep -i -r error /var/log/apache2/
sudo grep -i -r error /var/log/httpd/
Ubuntu and Debian users might also need to check through the compressed log files. This can be done using ‘zgrep’ instead, but due to its limitations, you can only search one log at the time, for example using this following command.
sudo zgrep error /var/log/apache2/error.log.2.gz
Not all errors logged by your web service necessarily mean there is something wrong with your server, but keep an eye out for any repeating problems like missing files in the example error below.
[Fri Jul 17 12:36:08.431065 2015] [:error] [pid 4649] [client 80.69.160.92] script '/var/www/html/index.php' not found or unable to start
You may also wish to enable more verbose logging if searching for errors is not yielding any results. The log output amount is controlled by a parameter called ‘LogLevel’ in the configuration file. On Debian and Ubuntu systems, open your configuration file with the following command.
sudo nano /etc/apache2/apache2.conf
With CentOS and other Red Hat based server use the command here instead.
sudo vi /etc/httpd/conf/httpd.conf
Find the LogLevel parameter and change it from the default ‘warn’ value to ‘debug’ instead, then save the file and exit. Again for any changes to be applied, the service needs to be reloaded. You can do this with one of the following commands appropriate for your system.
sudo systemctl reload apache2
sudo systemctl reload httpd
To generate some new entries using the new log levels, try to access your website again a couple of times even if it doesn’t work. The more verbose logs should help with narrowing down any underlying issues.
Check other services
If your website still won’t load after all the troubleshooting with Apache, check other related services on your cloud server such as databases, firewall and network connection, which also have their own troubleshooting instructions.
Do not hesitate to contact our support team. Remember to include any relevant information you may have discovered while troubleshooting, as every bit of detail, will be useful in further investigations.
При вводе команды sudo service apache2 reload
:
Job for apache2.service failed because the control process exited with error code. See «systemctl status apache2.service» and «journalctl -xe» for details.
Вывод при systemctl status apache2.service -l
:
● apache2.service — LSB: Apache2 web server
Loaded: loaded (/etc/init.d/apache2)
Active: active (exited) (Result: exit-code) since Вт. 2015-11-24 16:54:20 MSK; 19min ago
Docs: man:systemd-sysv-generator(8)
Process: 5848 ExecReload=/etc/init.d/apache2 reload (code=exited, status=1/FAILURE)
нояб. 24 17:07:43 artem-desktop apache2[4417]: *
нояб. 24 17:07:43 artem-desktop apache2[4417]: * Apache2 is not running
нояб. 24 17:07:43 artem-desktop systemd[1]: apache2.service: Control process exited, code=exited status=1
нояб. 24 17:07:43 artem-desktop systemd[1]: Reload failed for LSB: Apache2 web server.
нояб. 24 17:10:55 artem-desktop systemd[1]: Reloading LSB: Apache2 web server.
нояб. 24 17:10:55 artem-desktop apache2[5848]: * Reloading web server apache2
нояб. 24 17:10:55 artem-desktop apache2[5848]: *
нояб. 24 17:10:55 artem-desktop apache2[5848]: * Apache2 is not running
нояб. 24 17:10:55 artem-desktop systemd[1]: apache2.service: Control process exited, code=exited status=1
нояб. 24 17:10:55 artem-desktop systemd[1]: Reload failed for LSB: Apache2 web server.
Вывод при journalctl -xe
:
— The result is failed.
нояб. 24 17:10:55 artem-desktop polkitd(authority=local)[738]: Unregistered Authentication Agent for unix-process:5838:102243 (system bus name :1.126, object path /org/freedesktop
нояб. 24 17:10:55 artem-desktop sudo[5837]: pam_unix(sudo:session): session closed for user root
нояб. 24 17:11:04 artem-desktop pkexec[5869]: pam_unix(polkit-1:session): session opened for user root by (uid=1000)
нояб. 24 17:11:04 artem-desktop pkexec[5869]: pam_systemd(polkit-1:session): Cannot create session: Already running in a session
нояб. 24 17:11:04 artem-desktop pkexec[5869]: artem: Executing command [USER=root] [TTY=unknown] [CWD=/home/artem] [COMMAND=/usr/lib/update-notifier/package-system-locked]
нояб. 24 17:11:05 artem-desktop com.ubuntu.OneConf[2172]: WARNING:oneconf.hosts:Error in loading other_hosts file: [Errno 2] No such file or directory: ‘/home/artem/.cache/oneconf
нояб. 24 17:17:01 artem-desktop CRON[6066]: pam_unix(cron:session): session opened for user root by (uid=0)
нояб. 24 17:17:01 artem-desktop CRON[6067]: (root) CMD ( cd / && run-parts —report /etc/cron.hourly)
нояб. 24 17:17:01 artem-desktop CRON[6066]: pam_unix(cron:session): session closed for user root
нояб. 24 17:19:06 artem-desktop sudo[6112]: artem : TTY=pts/14 ; PWD=/etc ; USER=root ; COMMAND=/usr/bin/vim hosts
нояб. 24 17:19:06 artem-desktop sudo[6112]: pam_unix(sudo:session): session opened for user root by artem(uid=0)
нояб. 24 17:19:14 artem-desktop sudo[6112]: pam_unix(sudo:session): session closed for user root
нояб. 24 17:19:28 artem-desktop sudo[6118]: artem : TTY=pts/14 ; PWD=/ ; USER=root ; COMMAND=/usr/sbin/service apache2 reload
нояб. 24 17:19:28 artem-desktop sudo[6118]: pam_unix(sudo:session): session opened for user root by artem(uid=0)
нояб. 24 17:19:28 artem-desktop polkitd(authority=local)[738]: Registered Authentication Agent for unix-process:6119:153564 (system bus name :1.132 [/usr/bin/pkttyagent —notify-f
нояб. 24 17:19:28 artem-desktop systemd[1]: Reloading LSB: Apache2 web server.
— Subject: Unit apache2.service has begun reloading its configuration
— Defined-By: systemd
— Support: lists.freedesktop.org/mailman/listinfo/systemd-devel
—
— Unit apache2.service has begun reloading its configuration
нояб. 24 17:19:28 artem-desktop apache2[6129]: * Reloading web server apache2
нояб. 24 17:19:28 artem-desktop apache2[6129]: *
нояб. 24 17:19:28 artem-desktop apache2[6129]: * Apache2 is not running
нояб. 24 17:19:28 artem-desktop systemd[1]: apache2.service: Control process exited, code=exited status=1
нояб. 24 17:19:28 artem-desktop systemd[1]: Reload failed for LSB: Apache2 web server.
— Subject: Unit apache2.service has finished reloading its configuration
— Defined-By: systemd
— Support: lists.freedesktop.org/mailman/listinfo/systemd-devel
—
— Unit apache2.service has finished reloading its configuration
—
— The result is failed.
нояб. 24 17:19:28 artem-desktop sudo[6118]: pam_unix(sudo:session): session closed for user root
нояб. 24 17:19:28 artem-desktop polkitd(authority=local)[738]: Unregistered Authentication Agent for unix-process:6119:153564 (system bus name :1.132, object path /org/freedesktop
I removed apache2 before and I reinstalled it on ubuntu 14.04.
Now I want to restart apache.
Here is how apache was uninstalled:
sudo apt-get purge apache2 apache2-utils apache2.2-bin apache2-common
and
sudo apt-get autoremove
After re-installing I tried below
sudo service apache2 restart
but it gives
$ apache2: unrecognized service
When I check apache version
$ apache2 -v
Server version: Apache/2.4.7 (Ubuntu) Server built: Mar 10 2015
13:05:59
What am I missing?
I rebooted my vps but still it’s giving the same error.
asked May 21, 2015 at 17:41
You might need to reinstall the common package. Seems like you are missing the init script. You can check to see if apache2 is in the /etc/init.d/ directory..
ls /etc/init.d/
If it is missing you can try and reinstall common. Also you can run reinstall on apache2 as well to see if it replaces files that are missing.
sudo apt-get install --reinstall apache2.2-common
answered May 21, 2015 at 18:26
1
I am using Ubuntu 18.04 Subsystem for Windows 10
and I had that problem when starting my apache2 service for the first time,to fix that you have to recover your apache2-utils
by typing these commands in your terminal :
sudo apt-get remove --purge apache2 apache2-utils
sudo apt-get install --reinstall apache2 apache2-utils
sudo service apache2 start
and then check by:
sudo service apache2 status
Thomas
4,1955 gold badges21 silver badges28 bronze badges
answered Jun 1, 2019 at 10:07