Ubuntu ошибки apache

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.

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.

Многие новички, которые пытаются настроить свой домашний веб-сервер на основе Apache часто сталкиваются с ошибкой, что Apache не запускается. Благо сейчас в Ubuntu веб-сервер будет правильно работать по умолчанию и запустится, если вы не будете менять настройки, но раньше и в других дистрибутивах приходилось настраивать различные параметры и возникали ошибки.

В этой небольшой статье мы рассмотрим почему Apache не работает, что может стать причиной этой проблемы и как ее решить. Инструкция подойдет не только для Ubuntu, но и для других Linux дистрибутивов.

Вы можете столкнуться с такой проблемой по разным причинам, давайте сначала рассмотрим основные из них, чтобы вы знали что дальше делать:

  • Ошибка в конфигурационном файле — вы меняли конфигурацию и настроили что-то неправильно из-за этого программа не может запустится;
  • Права доступа — у программы нет прав доступа к каким-то важным для нее файлам, например, файлам логов, модулей или конфигурационным файлам;
  • Не запускается служба apache при загрузке, но при запуске из консоли все работает — проблема в том, что на момент запуска загружены еще не все необходимые службы;
  • Неверно указанно доменное имя — такая ошибка довольно часто встречается на локальных компьютерах;

А теперь рассмотрим более подробно почему так происходит и как решить проблему.

Как решить проблему с Apache?

Самое первое что вам нужно сделать в любом случае, если что-то не работает — это смотреть логи и информацию об ошибках. Только там вы сможете точно узнать что произошло. Самый простой способ это сделать, воспользоваться подсказкой systemd, которую она выдает при ошибке запуска:

See "systemctl status apache2.service" and "journalctl -xe" for details

То есть нам нужно выполнить systemctl status apache2.service или journalctl -xe чтобы получить больше сведений. Выполните сначала первую команду:

systemctl status apache2.service

Мы сразу же видим причину проблемы — ошибка в конфигурационном файле, в директиве Listen, а теперь пробуем другую команду:

journalctl -xe

Только ее нужно выполнять сразу же, как была выполнена попытка перезапуска apache, потому что скоро буфер лога будет затерт и вы там ничего не увидите. Но здесь сообщается то же сообщение об ошибке в конфигурационном файле, даже видно строку — 54. Еще можно посмотреть error.log, но туда сообщения пишутся не всегда:

cat /var/log/apache2/error.log

Дальше вы можете проверить конфигурационный файл на корректность с помощью такой команды:

apache2ctl -t

Тут будут показаны даже предупреждения, которые не влияют на работу сервиса. Все серьезные ошибки нужно исправить если таковые имеются, возможно именно они препятствуют запуску.

Следующая важная проблема — это права доступа. Если Apache запускается от имени пользователя www-data, то у этого пользователя должен быть доступ на чтение к папке где лежат документы веб-сайта, а также ко всем папкам выше нее, также должен быть доступ на чтение и запись для логов и конфигурационных файлов. Проверить права можно с помощью команды namei, это аналог ls, который отображает полное дерево прав:

namei -l /var/www/public_html/

Таким же образом проверяем папку с логами:

namei -l /var/log/apache2/

Как видите, у меня папка /var/www/public_html принадлежит пользователю root, но на папку public_html установлены права чтения и записи для всех пользователей. Поэтому проблем нет, а на папку с логами в качестве группы установлена adm, в эту группу входит пользователь www-data, так что тут тоже проблем нет. Если у вас что-то отличается и вы видите что прав недостаточно, то либо измените владельца папки с файлами веб-сайтов на www-data, либо дайте больше разрешений:

chown -R www-data /var/www/public_html/

Также, если в вашей системе включен SELinux, то вы можете его отключить на время, чтобы понять не в нем ли проблема:

setenforce 0

Другой момент, который может вызвать ошибку, это если на порту, который вы хотите использовать для веб-сервера уже запущен какой-то процесс, например, nginx или lighttpd, в таком случае, его нужно остановить:

sudo systemctl stop nginx
sudo systemctl stop lighttpd

Или вы можете попытаться изменить порт на другой, для этого откройте конфигурационный файл веб-сервера и найдите там строку Listen:

Listen 80

Если такой строки еще нет, то вы можете ее создать. Далее просто измените номер порта с 80 на любой удобный, например, 8080

Listen 8080

Дальше про ошибку старта при загрузке. Такая ошибка случалась в версиях ниже 2.2.4, если вы используете эту или более новую версию, то эта проблема вам не страшна. Она была вызвана тем, что Apache с SSL не хотел запускаться без папки /var/run/apache2, которой не было на момент загрузки. Самый простой способ решить проблему — отключить модуль ssl:

a2dismod ssl

Второй способ более сложный — добавьте в конфигурационный файл /etc/init.d/apache2 такую строку:

[ -d /var/run/apache2 ] || mkdir /var/run/apache2

Последняя проблема, о которой мы говорили — это когда неверно указанно имя сервера, на котором запускается Apache. Этой ошибке тоже были подвержены только ранние версии программы. Тогда при попытке запуска программа выдавала сообщение:

Failed to resolve server name for localhost

И дальше не запускалась. Чтобы решить эту проблему нужно было либо создавать виртуальные хосты, либо прописать в основном конфигурационном файле директиву ServerName, в которой будет указанно имя этого компьютера:

ServerName sergiy-pc

А также ассоциировать это имя с localhost в файле hosts:

sudo vi /etc/hosts

sergiy-pc localhost

Дальше было достаточно перезапустить Apache и все начинало работать.

Выводы

В этой статье мы рассмотрели несколько причин почему не запускается Apache и примеров их решения. Причин может быть множество, но мы разобрали только самые главные, которые встречаются наиболее часто. Надеюсь, эта информация была для вас полезной, если у вас остались вопросы, спрашивайте в комментариях! А для тех кого интересует еще один способ решения проблемы xampp apache не запускается для Windows есть видео:

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

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'

Artur Meinild's user avatar

asked May 29, 2015 at 20:48

Gautam Savaliya's user avatar

Gautam SavaliyaGautam Savaliya

2,3113 gold badges14 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's user avatar

Eliah Kagan

117k54 gold badges319 silver badges495 bronze badges

answered Aug 1, 2016 at 18:31

rancho's user avatar

10

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

Andrea Corbellini's user avatar

answered Aug 18, 2015 at 10:16

Arek's user avatar

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's user avatar

Parto

15k24 gold badges86 silver badges114 bronze badges

answered Mar 15, 2016 at 10:06

Rujika Rajan's user avatar

3

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's user avatar

Videonauth

33.1k16 gold badges104 silver badges120 bronze badges

answered Dec 27, 2016 at 7:12

Riyal Padhiyar's user avatar

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

iMarketingGuy's user avatar

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

Bruce Tong's user avatar

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

Kaushikdjay's user avatar

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

Thomas Venturini's user avatar

Thank you for your help! I was able to install correctly with 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 apache 2

It now works fine.

muru's user avatar

muru

194k53 gold badges475 silver badges725 bronze badges

answered Jan 16, 2017 at 1:41

Renata Sembay's user avatar

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

Ilias Koritsas's user avatar

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 on a2enconf)
  • /etc/apache2/conf-enabled — a2disconf (to turn back on a2enconf)

In my case, I had to those MODS enabled.

enter image description here

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

MadBoy's user avatar

MadBoyMadBoy

5611 gold badge5 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 Moro's user avatar

Andrea MoroAndrea Moro

4811 gold badge5 silver badges16 bronze badges

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

Понравилась статья? Поделить с друзьями:
  • Unb ошибка на стиральной машине haier как сбросить
  • Ubuntu ошибка репозиториев
  • Unassigned reference exception unity ошибка
  • Ubuntu ошибка при установке пакетов
  • Ubuntu ошибка при установке grub