Ошибка failed to start the apache http server

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

Установил apache на linux mint, при просмотре статуса Apache вылезает такая ошибка, помогите разобраться в проблеме.

    ● 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: failed (Result: exit-code) since Tue 2019-10-15 20:18:03 +07; 10min ago
  Process: 5060 ExecStart=/usr/sbin/apachectl start (code=exited, status=1/FAILURE)

окт 15 20:18:03 my-mint apachectl[5060]: AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive
окт 15 20:18:03 my-mint apachectl[5060]: (98)Address already in use: AH00072: make_sock: could not bind to address [::]:80
окт 15 20:18:03 my-mint apachectl[5060]: (98)Address already in use: AH00072: make_sock: could not bind to address 0.0.0.0:80
окт 15 20:18:03 my-mint apachectl[5060]: no listening sockets available, shutting down
окт 15 20:18:03 my-mint apachectl[5060]: AH00015: Unable to open logs
окт 15 20:18:03 my-mint apachectl[5060]: Action 'start' failed.
окт 15 20:18:03 my-mint apachectl[5060]: The Apache error log may have more information.
окт 15 20:18:03 my-mint systemd[1]: apache2.service: Control process exited, code=exited status=1
окт 15 20:18:03 my-mint systemd[1]: apache2.service: Failed with result 'exit-code'.
окт 15 20:18:03 my-mint systemd[1]: Failed to start The Apache HTTP Server.

задан 15 окт 2019 в 13:34

kirill568's user avatar

1

apachectl[5060]: (98)Address already in use: AH00072: make_sock: could not bind to address [::]:80

Ошибка говорит о том, что 80 порт уже занят.
Остановите службу, которая занимает порт. Для проверки:

sudo netstat -tpln | grep ":80"

Либо в конфиге apache2 смените порт на другой.

ответ дан 15 окт 2019 в 13:55

netsys's user avatar

netsysnetsys

663 бронзовых знака

Сменил порт на другой в файле /etc/apache2/ports.conf в строке Listen 80

ответ дан 15 окт 2019 в 13:58

kirill568's user avatar

kirill568kirill568

1571 серебряный знак9 бронзовых знаков

Apologies for not asking specifics before hand, but comment on this and I can try to update this answer to be more specific.

The error is pretty self-explanatory. Apache has a structure for loading modules attached to the service. On Ubuntu there are 3 important files for each module. Let’s look at the mpm_prefork module that you should probably have out of the box. In /etc/apache2/mods-enabled/ you’ll find a mpm_prefork.load and an mpm_prefork.conf file.

Read those with vi or nano like so nano /etc/apache2/mods-enabled/mpm_prefork.load In here, you’ll see that it’s looking for a companion binary file called /usr/lib/apache2/modules/mod_mpm_prefork.so. Notice how the path seems similar to the error you’re getting?

So in your case you appear to have a php7.0.load file which is looking for /usr/lib/apache2/modules/libphp7.0.so. You should look to see that file is indeed there or not by listing that directory with ls /usr/lib/apache2/modules/ Is it there?

If not, then I recommend trying to reinstall php, which wouldn’t be the worst idea since php7.0 is going to be deprecated soon anyways (Dec 3, 2018 to be exact).

So run the following:

dpkg --get-selections | grep php*  # list all php packages installed
sudo apt remove php7.0  # but replace php7.0 with whatever you installed
sudo apt update
sudo apt install php libapache2-mod-php


Introduction

Apache. The name no software guy is unfamiliar with. In the simplest of terms, it is the most widely used web-server for running and maintaining websites on the Internet. It is responsible for directing users on the internet to the desired HTTP directory. Given that it’s so popular, it still stands on its name while being free and open-source. How cool is that?

Despite how cool it sounds, I’m about to tell you something dreadful. With popular programs come popular error messages, and one such is the “failed to start apache http server” message. Don’t be disheartened just yet! Because the fix itself is way easier than running the server itself. If you can get your guts to run the server, you can fix the problem like so. All it takes is just a bit of understanding! 

In this article, we’ll try to break down the possible causes for encountering this error message, and provide you with their fixes all along.


Possible causes for ‘failed to start the apache http server’

No directory present for Apache Log files

The first possible reason for the failure of starting the apache http server is due to the absence of the log file directory for apache. Log files are extremely crucial for server management tools, which is why not having this directory straight out means that the apache server will be unable to run. This directory should usually be created automatically when you install apache. 

In many cases, it is possible that a disk-cleanup utility may have removed those log files, stating them as unnecessary. There sure are programs that have faint use of log files, but it isn’t the same for server management tools. Which is why you will need to create that directory.

Port is already occupied

The other very, very common reason for the error message to occur is that some other program is already occupying the same port, which apache is trying to use. The default port that apache tries to use is 80, but apache is not alone. Other tools like nginx also use the port 80 by default. This is because 80 is actually the default port for HTTP itself. 

Therefore, in order for apache to run, you either need to remove the program which is occupying port 80, or change the port of either apache or the other program so as to avoid conflicts and start the server smoothly.


How to fix ‘failed to start the apache http server’

Restart the Apache Server

The first thing you’d like to do before anything else is to see if restarting the apache server works out. This could help out in certain cases, and for many could turn out to be the only fix they require to abolish the error message. The best way to do this is to fully stop the server and than start it again, rather than using restart command:

$ sudo systemctl stop apache2.service 
$ sudo systemctl enable apache2.service 
$ sudo systemctl start apache2.service

If you don’t encounter any error while trying to use the above commands, then you have properly started the apache http server without any further errors. Also, notice the fact that I wrote apache2 instead of just apache. This is because the latest version of apache is above 2, so the service name has now changed to apache2 as well. If you’re using an older version, it is probably a good idea to switch. If you don’t want that, then make sure to type apache.service instead of apache2.service in the above commands. 

If the above hasn’t worked for you, try out the other methods that are discussed below. 

Create the directory for log files

As mentioned previously, not having the directory where the log files for apache are saved means that you’ll not be able to start the apache server. To fix this, simply create the directory by running:

$ mkdir -p /var/log/apache2

This should create the directory you’re looking for. However, if you’re using this command as a different user other than root, you’d see that the terminal is giving an output saying “permission denied”. Which is why, you will first need to login to the root user. Or else, you can also use the sudo command before to give superuser privileges to your current user. Try running the below command:

$ sudo mkdir -p /var/log/apache2

Now try starting the apache server once again to see if it works, by running:

$ sudo systemctl start apache2.service

If you see no error messages this time around, then you’ve successfully surpassed the error message! If fortune did not turn out to be true, and you still see errors, it probably means that this is not the issue, or at least, not the only issue. 

Stop/remove the program occupying the port

There are several ways to look into this solution for fixing the error message. The goal of this is to free up port 80 so that Apache can use it to run the server. But first, you need to figure out which program is actually occupying port 80. To do this, install a program called net-tools. If you’re using Ubuntu: you’d use the following command:

$ sudo apt-get install net-tools

Once the tool is installed, run the below command to see which program is occupying port 80:

$ sudo netstat -antup | grep 80

For example, look what I found in my case:

In the above image, I can see that port 80 is being occupied by the nginx server. So there are two things I could do to remove it’s occupation:

  1. Remove the Program entirely
  2. Disable it for a certain period
  3. Change the port for Apache

The choice is for you to make, for yourself. But I’ll show you all three.

The first option is to remove the program entirely. If you think that you don’t actually need the other program which is being used, you can remove it, by first figuring out its name like I did previously using the netstat command, and then use your package manager. In my case, it was nginx, so I’d use the following command to remove it:

$ sudo apt-get --purge remove nginx

Now try starting the apache server once again to see if it has worked out for you.

The next option is to disable the other program, for now at least. If you think you need to use both, at different intervals, then you can disable and enable the servers according to your demand. But if you wish to run them simultaneously, then you’ll need to change the port of at least one of the programs. For now, I’ll use the following commands respectively to disable nginx, to free up port 80:

$ sudo systemctl stop nginx 
$ sudo systemctl disable nginx

Once I’ve disabled it, now look what happens when I try out the netstat command once again:

$ sudo netstat -antup | grep 80

As you’d have probably noticed by now, the command returns you no output, as there is no program occupying port 80 at present.

Simple start the apache server now by running:

$ sudo systemctl start apache2.service

You should now successfully be able to start the apache http server without any further issues. 

There’s one last option that I’m left to show you, that is, to change the port for Apache. Though nor recommended, you can do this to run different servers at the same time, in case you need them all. 

Change the port for Apache

To change the port for Apache, first stop the apache server, bu running:

$ sudo systemctl stop apache2.service

Then, open up the ports.conf file using a text editor like nano, by using:

$ sudo nano /etc/apache2/ports.conf

inside this file, change the number 80 after listen to the port number you like. here, I’d like to use 8080, which should look something like this:

Once you’ve edited this file, you also need to make changes to the 000-default.conf file, located under the sites-enabled directory, so that the websites can recognise this new port. Open the file by running:

$ sudo nano /etc/apache2/sites-enabled/000-default.conf

Inside this file, you’d need to change the very first line, and change the number 80 to the new port, which in my case is 8080. After being changed, it should something like the one below:

After everything is set, try starting the server once again too see if the changes have taken effect:

$ sudo systemctl start apache2.service

This time around, if you use the same netstat command as previous, this is what you should be seeing if the changing was a success:

$ sudo netstat -antup | grep 80

Wala! Changing the port was a definite success! Now let’s take things to the minimal-extreme by checking if we can run nginx along with this server, both together. Once I start the nginx server once again, and when I ran netstat, look what I found:


Conclusion

Wohoooo! We now have both the servers up and running, without any conflicts, as well as without any error messages! As always, the choice is yours. If you think you need both of the servers, then using this method should probably be the correct way to do so. Otherwise, if you think that you only need apache, then taking this method is probably quite meaningless. But beware! It is also possible that some other application you’re running needs the other server to be run as well. So make sure you don’t remove it before clarifying that!



0

1

root@vm-9699334a:~# sudo systemctl status apache2
● apache2.service — The Apache HTTP Server
Loaded: loaded (/lib/systemd/system/apache2.service; disabled; vendor preset: enab
Drop-In: /lib/systemd/system/apache2.service.d
└─apache2-systemd.conf
Active: failed (Result: exit-code) since Sat 2020-05-09 19:43:59 UTC; 27min ago

May 09 19:43:59 vm-9699334a systemd[1]: Starting The Apache HTTP Server…
May 09 19:43:59 vm-9699334a apachectl[23308]: apache2: Could not open configuration f
May 09 19:43:59 vm-9699334a apachectl[23308]: Action ‘start’ failed.
May 09 19:43:59 vm-9699334a apachectl[23308]: The Apache error log may have more info
May 09 19:43:59 vm-9699334a systemd[1]: apache2.service: Control process exited, code
May 09 19:43:59 vm-9699334a systemd[1]: apache2.service: Failed with result ’exit-cod
May 09 19:43:59 vm-9699334a systemd[1]: Failed to start The Apache HTTP Server.
lines 1-13/13 (END)

Понравилась статья? Поделить с друзьями:
  • Ошибка failed to start precomp exe
  • Ошибка failed to start denuvo driver error code 2148204812
  • Ошибка failed to start denuvo driver error code 1450
  • Ошибка failed to set display mode
  • Ошибка failed to retrieve the install directory