Debian apache2 ошибка

8 сентября, 2020 11:28 дп
4 715 views
| Комментариев нет

Centos, Debian, LAMP Stack, Ubuntu

Эта серия мануалов поможет вам предотвратить или устранить самые распространенные ошибки, которые возникают при работе с веб-сервером 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 не содержит ошибок, вы получите такой результат:

Syntax OK

В зависимости от вашего дистрибутива 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, обычно они указывают на конкретную ошибку (предоставляя полезные для диагностики данные и коды ошибок).

Tags: Apache, apachectl, journalctl, systemctl

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.

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 webmaster@localhost 
   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.

Antanaclase

Posts: 6
Joined: 2013-07-03 08:37
Been thanked: 1 time

[SOLVED] Apache2 / Unable to start

#1

Post

by Antanaclase »

Hi everyone,

I’ve started using Linux for the first time a few days ago, as I tried to install a Home server. I’ve followed a tutorial for the most part, but I’m stuck at a weird issue. A few google searches didn’t help solving it :/

The issue:
If I type

I get

Code: Select all

Starting web server: apache2(98)Address already in use: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
Unable to open logs
Action 'start' failed.

However, a quick

gives this

Code: Select all

tcp        0      0 0.0.0.0:10000           0.0.0.0:*               LISTEN      2683/perl
tcp        0      0 0.0.0.0:21              0.0.0.0:*               LISTEN      2154/proftpd: (acce
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      2347/sshd
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      2469/mysqld
udp        0      0 0.0.0.0:21958           0.0.0.0:*                           1844/dhclient
udp        0      0 0.0.0.0:10000           0.0.0.0:*                           2683/perl
udp        0      0 0.0.0.0:68              0.0.0.0:*                           1844/dhclient
udp        0      0 192.168.2.107:123       0.0.0.0:*                           2011/ntpd
udp        0      0 127.0.0.1:123           0.0.0.0:*                           2011/ntpd
udp        0      0 0.0.0.0:123             0.0.0.0:*                           2011/ntpd

So… No port 80 is being used it seems here. I don’t get it. Most of the google search answer had another process running through port 80, and simply killing it was enough to solve the issue. It doesn’t seem to be the case for me…

Also I wonder whether this is related/normal:

Code: Select all

service apache2 stop
[ ok ] Stopping web server: apache2.
service apache2 stop
[ ok ] Stopping web server: apache2.
service apache2 stop
[ ok ] Stopping web server: apache2.
service apache2 stop
[ ok ] Stopping web server: apache2.

Should I be able to chain-stop apache2? Is this normal behaviour?

Thanks a lot for the answers, I a bit lost!

Last edited by Antanaclase on 2013-07-04 09:17, edited 1 time in total.




User avatar

dilberts_left_nut

Administrator
Administrator
Posts: 5296
Joined: 2009-10-05 07:54
Location: enzed
Has thanked: 8 times
Been thanked: 58 times

Re: Apache2 / Unable to start

#4

Post

by dilberts_left_nut »

OK.
I don’t know Raspbian or what, if anything, is different from vanilla debian.

Antanaclase wrote:I get

Code: Select all

Starting web server: apache2(98)Address already in use: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down

No other webservers been installed?
All net interfaces up and working?

Code: Select all

Unable to open logs
Action 'start' failed.

This also seems significant.
/var/log writable?

AdrianTM wrote:There’s no hacker in my grandma…


Antanaclase

Posts: 6
Joined: 2013-07-03 08:37
Been thanked: 1 time

Re: Apache2 / Unable to start

#5

Post

by Antanaclase »

I don’t think I have any other webserver installed, I strictly followed the tutorial, so I have those programs installed:
Apache2
PHP5
MySQL
ZenMap
PHPMyAdmin
Webmin
Webalizer

As I mentioned in my first post, this is my first «contact» with any Linux distribution, so I’m not exactly sure what you mean by

All net interfaces up and working?

or

/var/log writable?

Sorry for the hassle, I’m starting to wonder whether this was a good idea at all as an «introduction» to Linux.


js3915

Posts: 3
Joined: 2013-06-21 15:40

Re: Apache2 / Unable to start

#6

Post

by js3915 »

Sounds like you have a service already running.. Have you tried A. rebooting the computer.. and/or B seeing if you can open up the default apache2 webpage? simply by going to a browser and entering in http://localhost or the IP address of the machine your on?

Ive never used Raspberry PI i dont know whats different than pure debian.. I know in debian on a clean install if you run by root or sudo tasksel.. You can install a web-server by 1 click.. Ubuntu which is based on debian also running apt-get install tasksel then running sudo tasksel gives you same option but believe ubuntu versions you can select LAMP which is your Apache Mysql and PHP.. Hopefully someone will be able to help.. it might even be in your apache.conf file the error too you should be able to copy the file and paste here not sure on Raspberry but might be in /etc/apache2/apache2.conf or something like that


Antanaclase

Posts: 6
Joined: 2013-07-03 08:37
Been thanked: 1 time

Re: Apache2 / Unable to start

#7

Post

by Antanaclase »

Hi

I have rebooted the computer a few times already since the problem occured with no change.

The local IP of the computer has worked for a while, I could access the «PHPMyAdmin» configuration tool from another computer. But since the problem started, the load doesn’t seem to work.

Here is the apache2.conf file:

Code: Select all

#       /etc/apache2/
#       |-- apache2.conf
#       |       `--  ports.conf
#       |-- mods-enabled
#       |       |-- *.load
#       |       `-- *.conf
#       |-- conf.d
#       |       `-- *
#       `-- sites-enabled
#               `-- *
#
#
# * apache2.conf is the main configuration file (this file). It puts the pieces
#   together by including all remaining configuration files when starting up the
#   web server.
#
#   In order to avoid conflicts with backup files, the Include directive is
#   adapted to ignore files that:
#   - do not begin with a letter or number
#   - contain a character that is neither letter nor number nor _-:.
#   - contain .dpkg
#
#   Yet we strongly suggest that all configuration files either end with a
#   .conf or .load suffix in the file name. The next Debian release will
#   ignore files not ending with .conf (or .load for mods-enabled).
#
# * ports.conf is always included from the main configuration file. It is
#   supposed to determine listening ports for incoming connections, and which
#   of these ports are used for name based virtual hosts.
#
# * Configuration files in the mods-enabled/ and sites-enabled/ directories
#   contain particular configuration snippets which manage modules or virtual
#   host configurations, respectively.
#
#   They are activated by symlinking available configuration files from their
#   respective *-available/ counterparts. These should be managed by using our
#   helpers a2enmod/a2dismod, a2ensite/a2dissite. See
#   their respective man pages for detailed information.
#
# * Configuration files in the conf.d directory are either provided by other
#   packages or may be added by the local administrator. Local additions
#   should start with local- or end with .local.conf to avoid name clashes. All
#   files in conf.d are considered (excluding the exceptions noted above) by
#   the Apache 2 web server.
#
# * The binary is called apache2. Due to the use of environment variables, in
#   the default configuration, apache2 needs to be started/stopped with
#   /etc/init.d/apache2 or apache2ctl. Calling /usr/bin/apache2 directly will not
#   work with the default configuration.


# Global configuration
#

# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# NOTE!  If you intend to place this on an NFS (or otherwise network)
# mounted filesystem then please read the LockFile documentation (available
# at <URL:http://httpd.apache.org/docs/2.2/mod/mpm_common.html#lockfile>);
# you will save yourself a lot of trouble.
#
# Do NOT add a slash at the end of the directory path.
#
#ServerRoot "/etc/apache2"

#
# The accept serialization lock file MUST BE STORED ON A LOCAL DISK.
#
LockFile ${APACHE_LOCK_DIR}/accept.lock

#
# PidFile: The file in which the server should record its process
# identification number when it starts.
# This needs to be set in /etc/apache2/envvars
#
PidFile ${APACHE_PID_FILE}

#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 300

#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive On

#
# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 100

#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 5

##
## Server-Pool Size Regulation (MPM specific)
##

# prefork MPM
# StartServers: number of server processes to start
# MinSpareServers: minimum number of server processes which are kept spare
# MaxSpareServers: maximum number of server processes which are kept spare
# MaxClients: maximum number of server processes allowed to start
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule mpm_prefork_module>
    StartServers          5
    MinSpareServers       5
    MaxSpareServers      10
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>

# worker MPM
# StartServers: initial number of server processes to start
# MinSpareThreads: minimum number of worker threads which are kept spare
# MaxSpareThreads: maximum number of worker threads which are kept spare
# ThreadLimit: ThreadsPerChild can be changed to this maximum value during a
#              graceful restart. ThreadLimit can only be changed by stopping
#              and starting Apache.
# ThreadsPerChild: constant number of worker threads in each server process
# MaxClients: maximum number of simultaneous client connections
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule mpm_worker_module>
    StartServers          2
    MinSpareThreads      25
    MaxSpareThreads      75
    ThreadLimit          64
    ThreadsPerChild      25
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>

# event MPM
# StartServers: initial number of server processes to start
# MinSpareThreads: minimum number of worker threads which are kept spare
# MaxSpareThreads: maximum number of worker threads which are kept spare
# ThreadsPerChild: constant number of worker threads in each server process
# MaxClients: maximum number of simultaneous client connections
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule mpm_event_module>
    StartServers          2
    MinSpareThreads      25
    MaxSpareThreads      75
    ThreadLimit          64
    ThreadsPerChild      25
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>

# These need to be set in /etc/apache2/envvars
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}

#
# AccessFileName: The name of the file to look for in each directory
# for additional configuration directives.  See also the AllowOverride
# directive.
#

AccessFileName .htaccess

#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all
</Files>

#
# DefaultType is the default MIME type the server will use for a document
# if it cannot otherwise determine one, such as from filename extensions.
# If your server contains mostly text or HTML documents, "text/plain" is
# a good value.  If most of your content is binary, such as applications
# or images, you may want to use "application/octet-stream" instead to
# keep browsers from trying to display binary files as though they are
# text.
#
# It is also possible to omit any default MIME type and let the
# client's browser guess an appropriate action instead. Typically the
# browser will decide based on the file's extension then. In cases
# where no good assumption can be made, letting the default MIME type
# unset is suggested  instead of forcing the browser to accept
# incorrect  metadata.
#
DefaultType None


#
# HostnameLookups: Log the names of clients or just their IP addresses
# e.g., www.apache.org (on) or 204.62.129.132 (off).
# The default is off because it'd be overall better for the net if people
# had to knowingly turn this feature on, since enabling it means that
# each client request will result in AT LEAST one lookup request to the
# nameserver.
#
HostnameLookups Off

# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog ${APACHE_LOG_DIR}/error.log

#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn

# Include module configuration:
Include mods-enabled/*.load
Include mods-enabled/*.conf

# Include list of ports to listen on and which to use for name based vhosts
Include ports.conf

#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
# If you are behind a reverse proxy, you might want to change %h into %{X-Forwarded-For}i
#
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

# Include of directories ignores editors' and dpkg's backup files,
# see the comments above for details.

# Include generic snippets of statements
Include conf.d/

# Include the virtual host configurations:
Include sites-enabled/

Not sure it helps a lot though :/


User avatar

dilberts_left_nut

Administrator
Administrator
Posts: 5296
Joined: 2009-10-05 07:54
Location: enzed
Has thanked: 8 times
Been thanked: 58 times

Re: Apache2 / Unable to start

#8

Post

by dilberts_left_nut »

Maybe as a test, try changing your ports.conf to listen on a different port.

Is /var/log mounted on local storage?
If apache can’t write to it’s logfiles, you won’t have much info to track down this (or any other) issues. It may also be a reason for it to refuse to start.

AdrianTM wrote:There’s no hacker in my grandma…


Antanaclase

Posts: 6
Joined: 2013-07-03 08:37
Been thanked: 1 time

Re: Apache2 / Unable to start

#9

Post

by Antanaclase »

A bit of news:

Upon another reboot this morning, I could access the Webmin page from another computer through the local IP of the server. I could reach this page:
Image

However, according to the Terminal, «service apache2 status» is still «NOT running».

As for the log issue, there is an apache2 folder in /var/log, which contains access.log, error.log and other_vhosts_access.log. The last error message was on moday (about when the issue started occuring) and is:

Code: Select all

[Mon Jul 01 22:23:31 2013] [notice] caught SIGTERM, shutting down
(2)No such file or directory: apache2: could not open error log file /var/www/website1/log/error.log.
Unable to open logs
(2)No such file or directory: apache2: could not open error log file /var/www/website1/log/error.log.
Unable to open logs
(2)No such file or directory: apache2: could not open error log file /var/www/website1/log/error.log.
Unable to open logs
(2)No such file or directory: apache2: could not open error log file /var/www/website1/log/error.log.
Unable to open logs
(2)No such file or directory: apache2: could not open error log file /var/www/website1/log/error.log.
Unable to open logs
(2)No such file or directory: apache2: could not open error log file /var/www/website1/log/error.log.
Unable to open logs
(2)No such file or directory: apache2: could not open error log file /var/www/website1/log/error.log.
Unable to open logs
(2)No such file or directory: apache2: could not open error log file /var/www/website1/log/error.log.
Unable to open logs

I have fixed a part of the issue here, as the «website1» folder had a capital W, not small one, and that was not typed correctly in the configuration, but I still get the issue («unable to open logs»).
Do I have to manually create the «error.log» file the this folder? If so, through which command?

If I change the «NameVirtualHost» and «Listen» ports to 90 for instance (in ports.conf), I get the following error message:

Code: Select all

Starting web server: apache2[Thu Jul 04 10:49:20 2013] [warn] NameVirtualHost *:90 has no VirtualHosts


Antanaclase

Posts: 6
Joined: 2013-07-03 08:37
Been thanked: 1 time

Re: Apache2 / Unable to start

#10

Post

by Antanaclase »

Ok, I think I solved the issue!

I simply removed this part:

from the ports.conf.

I had this idea since I noticed I had another «Listen 80» in my own website.conf file (see C2 step, page 8 of the tutorial I followed):

Code: Select all

# oursites.conf
# KA Spencer 201211
#
# First, the listening port (if not specified elsewhere):
Listen 80
#
# Next, the IP address and port for the virtual host. This assumes
# that you have only one IP address and port for this server.
# Be sure to substitute your own parameters throughout this file!
NameVirtualHost 10.0.0.97:80
#
# Next, add the default server, because creating a virtual host
# causes Apache2 to ignore the default server configured in the
# /etc/apache2/sites-available/default file.
# If you do not do this,any html files in /var/www will be ignored!
<VirtualHost 10.0.0.97:80>
DocumentRoot /var/www
DirectoryIndex index.htm index.html index.php
</VirtualHost>
#
# Next your first virtual server details:
<VirtualHost 10.0.0.97:80>
ServerAdmin email@youraddress.com
ServerName oursite1
DocumentRoot /var/www/oursite1
DirectoryIndex index.htm index.html index.php
ErrorLog /var/www/oursite1/log/error.log
CustomLog /var/www/oursite1/log/access.log
</VirtualHost>
# This will allow you to access your "oursite1" website by that name

I wondered whether this would conflict apache2, and after removing it, I get:

Code: Select all

root@raspberrypi:/home/pi# service apache2 start
[ ok ] Starting web server: apache2.

Code: Select all

root@raspberrypi:/home/pi# service apache2 status
Apache2 is running (pid 3450).

I have one last question here. Is it better I keep the Listen 80 in the ports.conf or in this very file?

Thanks everyone for the help!



Common Apache Errors Troubleshooting

In the following of Apache tutorials, in this article, you will learn Common Apache Errors Troubleshooting. This tutorial series explains how to troubleshoot and fix some of the most common errors that you may encounter when using the Apache webserver.

Each tutorial in this series includes descriptions of common Apache configuration, network, filesystem, or permission errors. The series begins with an overview of the commands and log files that you can use to troubleshoot Apache. Subsequent tutorials examine specific errors in detail. To let this guide work better, try to purchase and use VPS or Linux web hosting.

Table of Contents

There are three main commands and a set of common log locations that you can use to get started troubleshooting Apache errors. Generally, when you are troubleshooting Apache, you will use these commands in the order indicated here, and then examine log files for specific diagnostic data.

The commands that you will commonly use to troubleshoot Apache across most Linux distributions are:

systemctl – Used to control and interact with Linux services via the systemd service manager.
journalctl – Used to query and view the logs that are generated by systemd.
apachectl – When troubleshooting, this command is used to check Apache’s configuration.

These commands, how to use them, and Apache’s log locations where you can find additional information about errors are described in further detail in the following sections.

Please Note: On Debian and Ubuntu systems, the Apache service and process name is apache2, whereas, on CentOS, Fedora, and other RedHat-derived systems, Apache’s service and process name is httpd. Apart from the differences between the service and running process names, starting, stopping, and checking Apache’s status, as well as logs with journalctl should work the same on any Linux system that uses systemd to manage the Apache service. Be sure to use the correct name for your Linux distribution.

systemctl Commands for Apache

To troubleshoot common Apache errors using the systemd service manager, the first step is to inspect the state of the Apache processes on your system. The following systemctl commands will query systemd for the state of Apache’s processes.

On Ubuntu and Debian systems run:

sudo systemctl status apache2.service -l --no-pager

The -l flag will ensure that output is not truncated or ellipsized. The –no-pager flag will make sure that output will go directly to your terminal without requiring any interaction on your part to view it. You should receive output like this:

Output

● 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  . . .

To inspect the Apache process on CentOS and Fedora systems run:

sudo systemctl status httpd.service -l --no-pager

Output

● 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

In either case, make a note of the Active line in the output. If your Apache server does not show active (running) as highlighted in the previous examples but you expect it should, there may be an error. Typically if there is a problem, you will have a line like the following in your output (note the highlighted failed portion):

Example Error Output

Active: failed (Result: exit-code) since Tue 2020-07-14 20:01:29 UTC; 1s ago

If there is a problem with your Apache process or configuration you can troubleshoot it further using the journalctl command.

journalctl Commands for Apache

To inspect the systemd logs for Apache, you can use the journalctl command. The systemd logs for Apache will usually indicate whether there is a problem with starting or managing the Apache process.

These logs are separate from Apache’s request and error logs. journalctl displays logs from systemd that describe the Apache service itself, from startup to shutdown, along with any process errors that may be encountered along the way.

On Ubuntu and Debian systems use the following command to examine the logs:

sudo journalctl -u apache2.service --since today --no-pager

The –since today flag will limit the output of the command to log entries beginning at 00:00:00 of the current day only. Using this option will help restrict the volume of log entries that you need to examine when checking for errors. You should receive output like the following:

Output

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.

If you are using a CentOS or Fedora-based system, use this version of the command:

sudo journalctl -u httpd.service --since today --no-pager

Output

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

If there is an error, you will have a line in the output that is similar to the following, with the main difference between Linux distributions being the highlighted yourhostname portion:

Example Error Output

Jul 14 20:13:37 yourhostname systemd[1]: Failed to start The Apache HTTP Server.

If your Apache server has errors in the journalctl logs like the previous example, then the next step to troubleshoot possible issues is investigating Apache’s configuration using the apachectl command-line tool.

Troubleshooting with apachectl

Most Linux distributions include the apachectl utility with Apache. apachectl is an invaluable tool to help detect and diagnose Apache configuration problems.

To troubleshoot issues using apachectl, test your Apache configuration using the apachectl configtest command. The tool will parse your Apache files and detect any errors or missing settings before attempting to start the server.

Run the command like this on Ubuntu, Debian, CentOS, and Fedora-based distributions:

sudo apachectl configtest

A working Apache configuration will result in an output like the following:

Output

Syntax OK

Depending on your Linux distribution, there may be other lines mixed in with the output, but the important line is the one that says Syntax OK.

If there is an error in your Apache configuration, like a directive that references a module that is not enabled or even a single typo, apachectl will detect it and attempt to notify you about the problem.

For example, attempting to use directives for an Apache module that is not enabled will result in apachectl configtest messages like the following.

Example Error Output

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.

In this example the ssl module is not enabled, so the SSLEngine directive generates an error when the configuration is tested. The last line also indicates that The Apache error log may have more information, which is the next place to look for more detailed debugging information.

Apache Log Files

Apache log files are a very helpful resource for troubleshooting. Generally, any error that you receive in a browser or other HTTP client will have a corresponding entry in Apache’s logs. Sometimes Apache will also output errors related to configuration, built-in modules, and other debugging information to its log files.

To examine log files for errors while troubleshooting Apache on a Fedora, CentOS, or RedHat server, examine the /var/log/httpd/error_log file.

If you are troubleshooting a Debian or Ubuntu derived system, examine /var/log/apache2/error.log for errors using a tool like tail or less. For example, to view the last two lines of the error log using tail, run the following command:

sudo tail -n 2 /var/log/apache2/error.log

Substitute the number of lines that you would like to examine in place of the number 2 in the command. On a CentOS or Fedora system, the log file to examine is /var/log/httpd/error_log.

An example error will resemble something like the following lines. Regardless of which Linux distribution you are using to run your Apache server:

Error Log Examples

[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

The two lines in this output are distinct error messages. They both reference the module causing the error (proxy in the first line, proxy_http in the second) and include an error code that is specific to the module. The first one, AH00957, indicates that the Apache server attempted to connect to a backend server (127.0.0.1 on port 9090 in this case) using the proxy module but failed to do so.

The second error is derived from the first: AH01114 is a proxy_http module error that also indicates that Apache was unable to connect to the configured backend server to make an HTTP request.

These example lines are just for illustration purposes. If you are diagnosing errors with your Apache server, chances are the error lines in your logs will have different contents than these. Regardless of your Linux distribution, the format of any error lines in your logs will include the relevant Apache module and error code, as well as a text description of the error.

Once you have an idea of what might be causing problems with your Apache server you can continue researching and troubleshooting the issue. The error code and text description are especially useful since they give you explicit and specific terms that you can use to narrow down the range of possible causes of a problem.

conclusion

Troubleshooting Apache errors can range from diagnosing errors with the service itself, to locating misconfigured options for modules, or to examining customized access control rules in detail. This introduction to diagnosing issues with Apache explained how to use a number of utilities to help narrow down the possible causes of errors. Usually, you will use these utilities in the same order, although you can always skip some, or start directly with examining logs if you have a general idea of what the problem might be. In case you are interested in learning more about Apache find our related articles on How to Secure Apache with Let’s Encrypt on Debian 10 OR How to secure Apache with Let’s Encrypt on Ubuntu 20.04.

However, as a general sequence for troubleshooting, it helps to be methodical and use these tools in the order described. Start troubleshooting with systemctl to examine the state of the Apache server. If you need more information, examine the systemd logs for Apache using the journalctl command. If the issue is still not apparent after checking the journalctl, testing Apache’s configuration using apachectl configtest is the next step. Finally, for in-depth troubleshooting, examining Apache’s log files will usually indicate a specific error, with helpful diagnostic messages and error codes.

I would restart Apache2 but there comes an Error

$ sudo service apache2 start

Starting web server apache2

Action 'start' failed.
The Apache error log may have more information.

But all error logs in «/var/log/apache2/» are empty.

Edit: The Files are at «/var/log/apache2» and there are several entries from previous Problems but this Task doesn’t create any new etry …

Where is the Problem?


I’ve Solved the Problem!

It was a error in the SSL Certificate and the path to the «error.log» are changed in the vHost configuration.

If you don’t need SSL (i don’t because i’m running a local system) simply disable all
vHost HTTPS/SSL entrys in the configuration by command line for line out.

asked Sep 24, 2013 at 7:57

fechnert's user avatar

fechnertfechnert

1,2252 gold badges12 silver badges30 bronze badges

8

Syntax errors in the config file seem to cause problems. I found what the problem was by going to the directory and excuting this from the command line.

httpd -e info 

This gave me the error

Syntax error on line 156 of D:/.../Apache Software Foundation/Apache2.2/conf/httpd.conf:
Invalid command 'PHPIniDir', perhaps misspelled or defined by a module not included in the server configuration

answered Feb 8, 2015 at 10:47

Toby Allen's user avatar

Toby AllenToby Allen

11k11 gold badges74 silver badges124 bronze badges

3

I also just ran in to a similar problem, that is service apache2 reload fails but prints no useful information. This is because the script in /etc/init.d/apache (on Debian, at least) eats the output of the apache2ctl configtest command it runs to sanitize the Apache config.

An easy solution to get a more meaningful explanation for the failure is to run apache2ctl configtest again yourself, which will print the (hopefully useful) error messages to the console.

answered Oct 21, 2014 at 7:21

pix's user avatar

pixpix

5,0522 gold badges23 silver badges25 bronze badges

2

Thanks, Tim! Big stumper for me. A few other details others may find helpful:

(Apache2 on Ubuntu 12.04)

I have two sites running on the same server and had just updated the SSL cert for one of them. Upon restarting the server, I got that cryptic message and neither site worked (obviously). I too found the redirect for the log files in the config files. I tracked that down and found the issue (in the log file for the site I had just updated).

My config files are located in /etc/apache2/sites-available

vim or cat the file (cat {filename}) and look for the ErrorLog line. That tells you where to look on your server. cat that file and the error message I found was:

[error] Unable to configure RSA server private key
[error] SSL Library Error: 185073780 error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch
[warn] RSA server certificate CommonName (CN) `<snip>.com' does NOT match server name!?

I had copied one of my cert files to the wrong directory. I simply moved it to the correct directory and everything was fine on the next start. (tip: where those file should be is also in the config file ;)

answered Mar 18, 2014 at 21:31

Ed Birm's user avatar

Ed BirmEd Birm

6576 silver badges6 bronze badges

in the apache virtualhost you have to define the path to the error log file.
when apache2 start for the first time it will create it automatically.

for example ErrorLog «/var/www/www.localhost.com/log-apache2/error.log» in the apache virtualhost..

answered Sep 24, 2013 at 8:04

drabo2005's user avatar

drabo2005drabo2005

1,0761 gold badge10 silver badges16 bronze badges

4

On XAMPP use

D:\xampp\apache\bin>httpd -t -D DUMP_VHOSTS

This will yield errors in your configuration of the virtual hosts

answered Jan 26, 2017 at 12:32

Pianoman's user avatar

PianomanPianoman

3372 silver badges11 bronze badges

If we have no entries in log files then we can try to debug apache2 using this command:

$ apache2 -S

or

$ apache2 -e debug

Possible output:

[Fri Apr 05 04:04:59.682880 2019] [core:warn] [pid 11086] 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

answered Apr 5, 2019 at 2:09

simhumileco's user avatar

simhumilecosimhumileco

32k16 gold badges137 silver badges115 bronze badges

1

I ran into this problem on the Raspberry Pi. After trying everything but a reinstall, on a whim, I deleted /var/run/apache2/apache2.pid. I restarted Apache and everything worked. Not sure how to explain that.

answered Aug 14, 2018 at 11:45

Michael Thompson's user avatar

I ran into this exact issue today. I had copied the entire /etc/httpd from RHEL 6 and put it onto a CentOS 6 system, and ensured all RPMs were installed.

Anytime apache would be started, it would silently fail. It took an strace to find the culprit: I was using CustomLog to call a program that was not installed on the target system. Once I installed the expected program, Apache HTTP Server started right up.

answered Feb 15, 2017 at 18:49

jaqque's user avatar

You have following ways to make it work:

  1. Delete /var/run/apache2/apache2.pid then check if its working

  2. You can disable SELinux and then check if it works. You can disable SELinux permanantly or temporarily by using https://linux4one.com/how-to-disable-selinux-on-centos-7/ tutorial

answered Jun 11, 2019 at 10:14

Mike Henry's user avatar

On Apache on Linux there might be a problem that the configuration cannot be checked because of a problem with environment variables not being set. This is a false positive which only occurs when running apache2 -S from commandline (See previous answer from @simhumileco). For instance Config variable ${APACHE_RUN_DIR} is not defined.

In order to fix this run source /etc/apache2/envvars from the commandline and then run `apache2 -S’ to get to the real (possible) problems.

root@fileserver:~# apache2 -S
[Thu Apr 30 10:42:06.822719 2020] [core:warn] [pid 24624] 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
root@fileserver:~# source /etc/apache2/envvars
root@fileserver:/root# apache2 -S
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message
VirtualHost configuration:
<----snip---->
ServerRoot: "/etc/apache2"
Main DocumentRoot: "/var/www/html"
Main ErrorLog: "/var/log/apache2/error.log"
Mutex ldap-cache: using_defaults
Mutex default: dir="/var/run/apache2/" mechanism=default
Mutex mpm-accept: using_defaults
Mutex watchdog-callback: using_defaults
PidFile: "/var/run/apache2/apache2.pid"
Define: DUMP_VHOSTS
Define: DUMP_RUN_CFG
User: name="www-data" id=33
Group: name="www-data" id=33
root@fileserver:/root#

answered Apr 30, 2020 at 8:44

Pianoman's user avatar

PianomanPianoman

3372 silver badges11 bronze badges

I have solved this same problem while configuring django in python with wsgi ,
I had installed libapache2-mod-python and libapache2-mod-wsgi-py3 at once ,so I removed libapache2-mod-python then it works fine for me

answered Jun 18, 2022 at 22:10

Sharad Bhandari's user avatar

solution on kali linux

httpd -e info

then i got this output

Failed to start apache2.service: Unit apache2.service is masked.

i removed mu ip mask then it worked properly

answered Oct 16, 2022 at 20:28

Israel's user avatar

1

Понравилась статья? Поделить с друзьями:
  • Deathloop windows 10 version 1909 ошибка
  • Death stranding сетевая ошибка
  • Death stranding ошибка установки
  • Death stranding при запуске выдает ошибку
  • Death stranding ошибка с0000005h