Ошибка 503 service unavailable iis

Обновлено 03.07.2020

HTTP Error 503

Добрый день! Уважаемые читатели и гости одного из крупнейших IT блогов России Pyatilistnik.org. В прошлый раз мы с вами научились чинить две вещи в Windows 10, это пресловутый черный экран и ошибку запуска в приложениях из-за отсутствия библиотеки vcruntime140.dll. Двигаемся дальше и сегодня решим еще один интересный пазл с веб сервисом IIS и ошибкой «HTTP Error 503. The service is unavailable«. Думаю, что мои грабли будут вам весьма интересны.

Описание ошибки 503 на IIS

Не так давно я устанавливал отказоустойчивую службу Remote Desktop Services High Availability на базе Windows Server 2019. Сами роли установились корректно и без ошибок в мастере, я успешно создал коллекцию, опубликовал RemoteApp приложения и хотел их протестировать, но какого же было мое удивление, когда я в место привычной формы авторизации увидел ошибку:

Service Unavailable: HTTP Error 503. The service is unavailable.

Service Unavailable: HTTP Error 503. The service is unavailable

Причины ошибки HTTP Error 503. The service is unavailable

Сразу могу сказать, что данную проблему вы можете встретить в любом продукте компании Microsoft, где в качестве веб движка используется служба IIS (Internet Information Services). Из популярных:

  • RDS фермы
  • Share Point
  • Exchange
  • Просто сайты на IIS

Сама проблема связана в связке IIS и Net.Framework. Обычно ошибка указывает на то, что веб-страница или запрос ресурса понятен серверу, но последний не может выполнить его по той или иной причине, или же из-за банальной перегрузки, когда не хватает ресурсов.

Методы устранения ошибки 503 на IIS

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

  • Отсутствие прав у учетной записи, которая запускает пул приложений
  • Вы запускаете пул в режиме 32 бита
  • У вас просто не работает пул приложений
  • Проблема с NET.Framework
  • Проблема на уровне операционной системы из-за ошибок целостности

Переустановка системы

Как бы это смешно не звучало, но в последнем случае у меня после того, как я все перепробывал чтобы устранить ошибку 503 на IIS, уже кончились идеи и я просто снес все так как система была чистая и поставил заново, но уже более свежий дистрибутив и о чудо проблема ушла.

Не знаю, в чем было дело, то ли глюки при обновлении Windows Server 2019, то ли что-то со сборкой которая у меня была, не могу точно сказать. До переустановки у меня была версия Windows 1809 (Сборка ОС 17763.1282)

Определение версии на сервере с ошибкой Service Unavailable: HTTP Error 503. The service is unavailable

После переустановки я поставил версию от июня 2020. Когда я уже в ней запускал сайт RDweb на ферме RDS, то сервис ответил корректно и HTTP Error 503 я не увидел.

Так, что если у вас только, что установленная Windows Server 2019, то попробуйте ее снести и установить заново, это может быть куда быстрее чем заниматься траблшутингом, самое ценное это ваше время, лучше уж провести его полезнее.

Проверка работы NET.Framework

По умолчанию в Windows Server 2019 при установке добавляется NET.Framework версии 4.7. Очень часто он может быть добавлен кривовато. В случае с Remote Desktop Services мне пришлось:

  • Удалить роль IIS и RDS
  • Удалить компонент NET.Framework
  • Скачать NET.Framework версии 4.7. Скачиваем потому, что после его удаления у вас не будет работать диспетчер серверов и установка из PowerShell.
  • Установить NET.Framework версии 4.7
  • Устанавливаете IIS
  • Устанавливаете RDS

В результате данного шаманства в сможете запустить RDweb на вашей RDS ферме минуя ошибку «Service Unavailable: HTTP Error 503. The service is unavailable».

Но перед всеми этими рокировками я вам советую, как и в случае с зависанием пула IIS обратиться к логам и попытаться там найти, что-то что даст нам направление для поиска информации. Напоминаю посмотреть логи Windows вы можете через оснастку «Просмотр событий» или веб-сервис Windows Admin Center. Советую смотреть четыре журнала. Первые два стандартные, это «Система» и «Приложения». Например вы можете увидеть вот такое событие с предупреждением:

Код ID 1309

Код ID 1309: Event code: 3005
Event message: Возникло необработанное исключение.
Event time: 30.06.2020 18:34:41
Event time (UTC): 30.06.2020 15:34:41
Event ID: aa3cbb1255f3432d813e6c5cb75395ed
Event sequence: 14
Event occurrence: 1
Event detail code: 0

Application information:
Application domain: /LM/W3SVC/1/ROOT/RDWeb/Pages-2-132380048755425068
Trust level: Full
Application Virtual Path: /RDWeb/Pages
Application Path: C:WindowsWebRDWebPages
Machine name: RDSH03

Process information:
Process ID: 3416
Process name: w3wp.exe
Account name: IIS APPPOOLRDWebAccess

Exception information:
Exception type: NullReferenceException
Exception message: Ссылка на объект не указывает на экземпляр объекта.
в Microsoft.TerminalServices.Publishing.Portal.FormAuthentication.TSFormAuthTicketInfo..ctor(HttpContext objHttpContext)
в ASP.ru_ru_default_aspx.<GetAppsAsync>d__0.MoveNext()
— Конец трассировка стека из предыдущего расположения, где возникло исключение —
в System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
в System.Web.UI.PageAsyncTaskManager.<ExecuteTasksAsync>d__3.MoveNext()
— Конец трассировка стека из предыдущего расположения, где возникло исключение —
в System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
в System.Web.UI.Page.<ProcessRequestAsync>d__554.MoveNext()

Request information:
Request URL: https://rdsh03.root.pyatilistnik.org:443/RDWeb/Pages/ru-RU/Default.aspx
Request path: /RDWeb/Pages/ru-RU/Default.aspx
User host address: 192.168.31.100
User:
Is authenticated: False
Authentication Type:
Thread account name: IIS APPPOOLRDWebAccess

Thread information:
Thread ID: 7
Thread account name: IIS APPPOOLRDWebAccess
Is impersonating: False
Stack trace: в Microsoft.TerminalServices.Publishing.Portal.FormAuthentication.TSFormAuthTicketInfo..ctor(HttpContext objHttpContext)
в ASP.ru_ru_default_aspx.<GetAppsAsync>d__0.MoveNext()
— Конец трассировка стека из предыдущего расположения, где возникло исключение —
в System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
в System.Web.UI.PageAsyncTaskManager.<ExecuteTasksAsync>d__3.MoveNext()
— Конец трассировка стека из предыдущего расположения, где возникло исключение —
в System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
в System.Web.UI.Page.<ProcessRequestAsync>d__554.MoveNext()
Custom event details:

Из которого понятно, что у меня не запущен пул. Откройте оснастку IIS и перейдите в раздел «Пулы приложений». Далее найдите нужный, в моем примере это RDWebAccess. Как видно у него статус «Остановлено», попробуйте его запустить.

Запуск пула в IIS при ошибке 503

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

  • Microsoft-Windows-IIS-Configuration/Administrative
  • Microsoft-Windows-IIS-Configuration/Operational

Журналы, где можно искать события по ошибке Service Unavailable: HTTP Error 503. The service is unavailable

Так же что-то полезное вы можете найти в текстовом файле располагающемся по пути:

C:WindowsSystem32LogFilesHTTPERR

Как видно из файла у меня был выключен пул «2020-07-01 08:34:12 ::1%0 62570 ::1%0 443 HTTP/2 GET /RDWeb 5 503 1 Disabled RDWebAccess». У вас может быть тут другая ошибка.

C:WindowsSystem32LogFilesHTTPERR

Вы можете выполнить в PowerShell вот такой запрос по получению информации из данного файла, только для 503 кода.

Get-ChildItem -Path ‘C:windowssystem32LogFilesHTTPERR’ -Include *.log -Recurse | Where-Object LastWriteTime -gt (Get-Date).AddDays(-7) | Select-String -SimpleMatch ‘ 503 ‘

Получение информации из HTTPERR’ по ошибке 503

Отключение 32 битного режима на пуле IIS

В журнале Microsoft-Windows-IIS-W3SVC-WP вы можете увидеть ошибку с кодом события: 2282, где:

Не удалось загрузить модуль DLL из-за ошибки в конфигурации. Текущая конфигурация поддерживает только загрузку образов для x86 архитектуру процессора. Поле данных содержит номер ошибки.

По умолчанию 32-разрядная поддержка отключена в пулах приложений. Если не требуется поддержка 32-разрядных, проверьте параметры каждого из пулов приложений убедитесь, что значение Разрешить 32-разрядные приложения имеет значение False.

Откройте дополнительные параметры у нужного пула, через контекстное меню.

Отключение 32 битного режима у пула IIS

Еще раз проверьте что параметр Enable32bitAppOnWin64 (Разрешить 32-разрядные приложения) имеет значение «False».

Проверка пула IIS на параметр Enable32bitAppOnWin64

Подробнее об этом вот тут — https://support.microsoft.com/ru-ru/help/2619402/error-503-service-unavailable-when-you-browse-windows-sbs-websites

Проверка учетной записи от которой запускается пул

Я очень часто встречал безалаберных системных администраторов, которым было лень создавать отдельные учетные записи для каждой службы или сервиса с которой они работают. Они делали просто, запускали все из под себя с максимальными правами или для теста так делали и забывали, что так оставили. Потом с течением времени учетную запись могут отключить или сменить пароль, что сразу делает ваш пул неработоспособным, он просто не может запустить его. Исходя из этого проверьте данную ситуацию. В дополнительных параметрах найдите раздел «Удостоверение» и посмотрите от имени кого у вас запущен ваш пул, по умолчанию должна быть встроенная учетная запись «ApplicationPoolidentity».

Проверка учетной записи от которой запускается пул

При необходимости вы можете выбрать другую учетную запись для запуска пула. После изменения, обязательно перезапустите пул, а лучше саму службу IIS.

Выбор учетной записи от имени которой запускается пул IIS

Отключение Load User Profile на пуле IIS

Когда пользователь входит в систему в интерактивном режиме, система автоматически загружает профиль пользователя. Если служба или приложение олицетворяет пользователя, система не загружает профиль пользователя. Поэтому служба или приложение должны загрузить профиль пользователя с помощью LoadUserProfile .

Службы и приложения, которые вызывают LoadUserProfile, должны проверить, есть ли у пользователя временный профиль. Если пользователь имеет перемещаемый профиль, указать путь к нему в качестве lpProfilePath члена PROFILEINFO.

Для IIS этот параметр указывает, должна ли служба загружать профиль пользователя для удостоверения пула приложений. Если значение этого параметра «True», то служба IIS загружает профиль пользователя для удостоверения пула приложений. Если необходимо поведение  IIS 6.0 без загрузки профиля пользователя для удостоверения пула приложений задайте значение «False«. Так, что если получаете «HTTP Error 503. The service is unavailable» и ничего не помогает, то пробуем его отключить.

Отключение Load User Profile на пуле IIS

Не создает временный файл конфигурации пула

Ошибку «Service Unavailable: HTTP Error 503. The service is unavailable» вы легко можете ловить из-за того, что ваш пул по какой-то причине не может создать временный файл конфигурации и об этом может свидетельствовать предупреждение в логах:

Службе активации процессов Windows не удалось создать файл конфигурации пула приложений для пула приложений < DefaultAppPool >. Тип ошибки: «5». Чтобы решить эту проблему, убедитесь, что файл applicationhost.config указан правильно, и повторите последние изменения конфигурации. Поле данных содержит номер ошибки.

Подробнее об этом на — https://support.microsoft.com/en-in/help/4050891/error-http-503-and-was-event-5189-from-web-applications-on-windows-10

Все происходит по причине того, что служба активации Windows (WAS) создает временный файл конфигурации для каждого пула приложений IIS в папке C:inetpubtempappPools во время обычной работы.

На начальном этапе обновления «Центр обновления Windows» сканирует существующие папки и файлы и записывает их пути для восстановления после обновления. Однако, поскольку файлы конфигурации являются временными, они удаляются при остановке WAS.

На следующем этапе Центра обновления Windows эти ранее отсканированные файлы и папки копируются во временную папку обновления. После обновления Windows «Центр обновления Windows» создает символическую ссылку на каждую папку, которая была скопирована во временное местоположение обновления, прежде чем он пытается восстановить эти файлы и папки в их исходное местоположение.

Однако поскольку эти временные файлы конфигурации больше не существуют, Центр обновления Windows не удаляет символические ссылки.

Когда WAS пытается запустить как рабочий процесс IIS, он не создает временную папку для записи конфигурации из-за символических ссылок. Поэтому Http.Sys возвращает ошибку HTTP 503.

Чтобы решить эту проблему, вручную удалите символические ссылки, созданные «Центром обновления Windows». Для этого выполните следующие действия:

  • Из командной строки от имени администратора

net stop WAS /y
rmdir /s /q C:inetpubtempappPools
net start W3SVC

  • Из оболочки PowerShell в режиме администратора

Stop-Service -Force WAS
Remove-Item -Recurse -Force C:inetpubtempappPools*
Start-Service W3SVC

Удаление временных файлов конфигурации пула в IIS

Два сайта на 443 порту

Был интересный случай в прошлом, мне нужно было перенести один сайт с IIS на другой сервер. После переноса вместо сайта я видел уже вам известную ошибку «Service Unavailable: HTTP Error 503. The service is unavailable». Самое интересное, что ошибка была только для HTTPS, в то время как HTTP работал нормально. Напоминаю, что по умолчанию https использует порт 443, зная это я решил посмотреть, что слушает порт, можно было конечно воспользоваться утилитами netstat или TCPView, но я пошел в тот момент через PowerShell. Введите команду, чтобы посмотреть, что порт слушается.

Get-NetTCPConnection -LocalPort 443 -State Listen

Как видно сервер слушается.

Проверка порта 443 на доступность через PowerShell

Если вы когда-нибудь столкнетесь с такой проблемой как 503 ответ, то попробуйте остановить службу веб-публикации

Stop-Service -Name w3svc -PassThru

И после этого опять запустить команду на прослушивание, если и в этом случае вы видите, что 443 порт ответил, то поздравляю у вас есть другой сервис мешающий IIS.

Остановка службы IIS

Если это сервер, который вы унаследовали, может быть нелегко определить, что прослушивает этот конкретный порт. Я установлю модуль PowerShell с именем Carbon (https://www.powershellgallery.com/packages/Carbon/) из галереи PowerShell, чтобы определить, что происходит.

Install-Module -Name Carbon -Force -AllowClobber

Когда веб-сервер не-IIS установлен в Windows, он устанавливает ACL для порта, который будет прослушивать. Вы можете увидеть ACL, который ссылается на порт 443.

То же самое через cmd — netsh http show urlacl

На самом деле, есть две записи для порта 443. Тот, у кого GUID все в порядке, так как он предназначен только для конкретного приложения через заголовок узла, а не по всему пространству имен.

Get-HttpUrlAcl

Второе я вычислил через TCPView, это было приложение Dell EqualLogic SAN Headquarters, установленное на этом конкретном сервере, оно вызывало проблему, поэтому я решил удалить его, так как оно больше не нужно.

Dell EqualLogic SAN Headquarters

Хоть я и удалил Dell EqualLogic SAN Headquarters с сервера, это не удалило ACL, назначенный порту 443.

Удаление ACL веб-сервера

Поскольку деинсталляция приложения не решила проблему, я решил принудительно удалить ACL

Revoke-HttpUrlPermission -Url https://+443/ -Principal ‘NT AUTHORITYSYSTEM’

То же самое через cmd — netsh http delete urlacl url = [вставить URL]

После удаления этой записи и перезапуска веб-службы проблемы с прослушиванием IIS через порт 443 были решены.

Кстати можно в логах посмотреть кто установил ACL, но там не всегда все подробно. Выполните:

Get-WinEvent -FilterHashtable @{LogName=’System’;ProviderName=’Microsoft-Windows-HttpEvent’;Level=4} -MaxEvents 1 | Select-Object -Property Message

Запись в просмотре событий кто добавил ACL веб-сервера

Дополнительные методы

  1. Перезагрузить сайт, через клавиши CTRL+F5
  2. Перезагрузите модем или компьютер
  3. Очистить кеш браузера
  4. Проверьте настройки прокси
  5. Если ошибку получаете в каком-то сервисе на телефоне, то попробуйте обновить приложение
  6. Проверка диска C: на ошибки

TL;DR:

The 503 response from the IIS machine, Service Unavailable, is the result of repeated application crashes. Since the w3wp.exe worker process, created by IIS to execute a web application, is crashing frequently, the respective IIS application pool is turned off. This is a feature of IIS, at Application Pool level, called Rapid-Fail Protection. It helps prevent consuming valuable system resources creating a worker process that crashes anyway, soon after spawning.

  • Evidence of repeated w3wp.exe crashes and Rapid-Fail Protection may be found in Windows Events, in the System log with Source=WAS.
  • Evidence of what causes the w3wp.exe to crash may be found in Windows Events, in the Application log: second-chance crashing exceptions with w3wp.exe.

Collecting the IIS basic troubleshooting info helps expedite investigation for the root cause of application crashes. Follow the steps at http://linqto.me/iis-basic-files for instructions.
In many cases, it may be needed to collect memory dumps to study the exceptions causing the crash: see article at http://linqto.me/dumps.

If we’re looking at the reference list of responses that IIS could send, an HTTP response status 503 means Service Unavailable. In most of the cases, we have a 503.0, Application pool unavailable; and when we check the corresponding application pool, it shows “Stopped”.

Believe it or not, that is actually a feature in IIS acting: the Rapid-Fail Protection. If the hosted application is causing the crash of its executing process for 5 times in less than 5 minutes, then the Application Pool is turned off automatically. These values are the default values; but you get the point.

Img 1, Rapid-Fail Protection settings for an Application PoolImg 1, Rapid-Fail Protection settings for an Application Pool

Rapid-Fail Protection

But why turning off the application pool at all? Why is IIS doing that?

You see, there is an IIS component called WAS, Windows (Process) Activation Service, that is creating and then monitoring the worker processes – w3wp.exe – for application pools. These are the IIS processes that are loading and then executing the Web apps, including the Asp.Net ones. These are the processes responding to HTTP requests.

If a worker process crashes, WAS would immediately try to create a new process for the Application Pool; because the Web apps needs to continue serving requests. But if these processes are repeatedly crashing, soon after being created, WAS is going to “say”:

I keep creating processes for this app, and they crash. It is expensive for the system to create these processes, which crash anyway. So why don’t I stop doing that, marking the Application Pool accordingly (Stopped), until the administrator is fixing the cause. Once the condition causing the crashes is removed, then the administrator may manually re-Start the application pool.

This WAS is reporting stuff in Windows Events, in the System log. So, if we open the Events Viewer, go to System log and filter by Event Sources=WAS, we may see a pattern like this:

Img 2, Windows Events by WAS while monitoring w3wp.exeImg 2, Windows Events by WAS while monitoring w3wp.exe

There is a pattern to look for: Usually 5 Warning events 5011, for same application pool name, within a short time frame; if the PIDs, Process ID, in the Warning events are changing, it is a sign that the previous w3wp.exe instance was “killed”, it ended for some reason:

A process serving application pool ‘BuggyBits.local’ suffered a fatal communication error with the Windows Process Activation Service. The process id was ‘6992‘. The data field contains the error number.

… and then followed by an Error event 5002 for that same application pool name:

Application pool ‘BuggyBits.local’ is being automatically disabled due to a series of failures in the process(es) serving that application pool.

This behavior – turning off the application pool – is also seen when WAS can’t start the worker process at all. For instance when the application pool identity has a wrong or non-decipherable password: WAS can’t (repeatedly) start the w3wp.exe with the custom account that was set for the application pool. In Windows Events we would see Warnings/Errors from WAS like:

Event ID 5021 when IIS/WAS starts: The identity of application pool BuggyBits.local is invalid. The user name or password that is specified for the identity may be incorrect, or the user may not have batch logon rights. If the identity is not corrected, the application pool will be disabled when the application pool receives its first request.  If batch logon rights are causing the problem, the identity in the IIS configuration store must be changed after rights have been granted before Windows Process Activation Service (WAS) can retry the logon. If the identity remains invalid after the first request for the application pool is processed, the application pool will be disabled. The data field contains the error number.

Event ID 5057 when app is first accessed: Application pool BuggyBits.local has been disabled. Windows Process Activation Service (WAS) did not create a worker process to serve the application pool because the application pool identity is invalid.

Event ID 5059, service becomes unavailable: Application pool BuggyBits.local has been disabled. Windows Process Activation Service (WAS) encountered a failure when it started a worker process to serve the application pool.

It is HTTP.SYS, for the inquisitive

When the application pool is turned off, hence we don’t have a w3wp.exe to process on requests for it, we’re having the HTTP.SYS driver responding status 503 instead of IIS. Remember that IIS is just a user-mode service making use of the kernel-level HTTP.SYS driver?

Img 3, HTTP.SYS validates and queues requests for IIS to pick and processImg 3, HTTP.SYS validates and queues requests for IIS to pick and process

With a normal, successful request, we have the IIS responding:

Img 4, Success response 200; in Response headers, the Server is IISImg 4, Success response 200; in Response headers, the Server is IIS

But when the application pool is down, the request does not even reach IIS. The response comes from HTTP.SYS, not from the w3wp.exe:

Img 5, With a 503 Response, the Server header is HTTP.SYSImg 5, With a 503 Response, the Server header is HTTP.SYS

Without a w3wp.exe to process the requests which arrived for an application pool, HTTP.SYS, while acting as a proxy, basically says:

Look, dear client, I tried to relay your request to IIS, to its w3wp.exe process created to execute the called app.
But the app or its configuration is repeatedly crashing the worker process, so creation of new processes ceased.
Hence, I had no process where to relay your request; there is no service ready to process your request.

Sorry: 503, Service Unavailable.

Why is w3wp.exe worker process failing?

I think of an IIS application pool as:

  • A queue for requests, in the kernel, maintained the HTTP.SYS driver; see it in a command-line console with
    netsh http show servicestate
  • Settings on how to create a w3wp.exe IIS worker process and how it should behave.
    • This process will load and execute our web application, most commonly an Asp.Net/NET Framework application.

As with all applications, exceptions happen, unforeseen errors. They all start as first-chance exceptions.

  • Most of the first-chance exceptions are handled and they never hurt the app or its executing process.
    They are handled either by the code of the application, or by the Asp.Net framework itself.
    • If the unhandled exception happens in the context of executing an HTTP request, the Asp.Net Framework will do its best to treat (handle) it by wrapping it and generating an error page, usually with an HTTP response status code of 500, Server-side execution error.
      The exception that was not handled by the developer’s code gets handled by the underlying framework.
  • Some exceptions are unhandled, not treated by any code in the process, so they become the so-called second-chance / process-crashing exceptions.
    • When these happen, the operating system simply terminates the process that generated them; all the virtual memory of the process is flushed away into oblivion.
    • Exceptions occurring outside the context of a request processing (such as during application startup) have more chances to become second-chance, crashing exception.

Fortunately, these exceptions – first-chance or second-chance – may leave traces. The first place to look at is in the Windows Events, Application log.

As an illustration, the code of my application running in the BuggyBits.local application pool generated the following:

Img 6, First-chance exception by app in .NET RuntimeImg 6, First-chance exception by app in .NET Runtime

Since the exception could not be handled by the Asp.Net, it immediately became a second-chance exception, causing Windows to terminate the w3wp.exe in the same second:

Img 7, Second-chance exception crashing w3wp.exeImg 7, Second-chance exception crashing w3wp.exe

Pings from WAS to check on w3wp.exe

If you notice the time-stamp in the capture above, it corresponds to a Warning event from WAS in the System log, telling that the worker process did not respond (Img 2).

This response does not refer to the HTTP request/response; it refers to pings from WAS.

Remember that I said WAS is creating the worker processes, w3wp.exe, but also it monitors them. It has to know if the worker process is healthy, if it can still serve requests. Of course, WAS is not able to know everything about the health of a w3wp.exe; many things could go wrong with the code of our app. But at least it can send pings to that process.

Illustrating with the Advanced Settings of an application pool, WAS is sending pings to its instances of w3wp.exe, every 30 seconds. For each ping, the w3wp.exe (that PID) has 90 seconds to respond. If no ping response is received, WAS concludes that the process is dead: a crash or hang happened – no process thread is available to respond to the ping. Notice that we also have other time limits too that WAS is looking on.

Img 8, Setting process pings from WAS to w3wp.exe(s)Img 8, Setting process pings from WAS to w3wp.exe(s)

More on exceptions

It may happen that, even looking in Windows Events > Application log, we still don’t know why our w3wp.exe is crashing or misbehaving. I’ve seen cases where the exceptions are not logged in Windows Events. In such cases, look in the custom logging solution of the web application, if it has one.

Lastly, if we don’t have a clue about these exceptions, if we have no traces left, we could attach a debugger to our w3wp.exe and see what kind of exceptions happen in there. Of course, we would need to reproduce the steps triggering the bad behavior, when using the debugger.

We can even tell that debugger to collect some more context around the exceptions, not just the exceptions itself. We could collect the call stacks or memory dumps for such context.

One such debugging tool is the command-line ProcDump. It does not require an installation; you only need to run it from an administrative console.

Let’s say I put my ProcDump in E:Dumps. Before using it, I must determine the PID, Process ID of my faulting worker process w3wp.exe:

E:Dumps>C:WindowsSystem32InetSrvappcmd.exe list wp

Then, I’m attaching ProcDump to the PID, redirecting its output to a file that I can later inspect:

E:Dumps>procdump.exe -e 1 -f "" [PID-of-w3wp.exe] > ProcDump-monitoring-log.txt

If my Windows has an UI and I’m allowed to install diagnosing apps, then I prefer Debug Diagnostics. Its UI makes it easier to configure data collection, and it determines the PID of w3wp.exe itself, based on the app pool selected. Debug Diag is better suited to troubleshoot IIS applications.

Both Debug Diag and Proc Dump are free tools from Microsoft, widely used by professionals in troubleshooting. A lot of content is available on the Web on how to use these.

A natural continuation to this article is the one I wrote about exceptions, exception handling, and how to collect memory dumps to capture exceptions or performance issues:

  • About exceptions and capturing them with dumps

Aside: Just in case you are wondering what I use to capture screenshots for illustrating my articles, check out this little ShareX application in Windows Store.

I’m really new to setting up web servers in general. I’ve got IIS 8 on Windows 8, and I’m trying to set up a little site locally, while doing some development. In IIS I choose Add Site, give a name, points to a location where I have a index.html file (I’ve tried different locations, latest in a c:inetpubwwwroottest -folder) and otherwise use all default settings. However, when I try to browse to localhost I get

HTTP Error 503. The service is unavailable.

I’ve verified the pool is started, and I’ve given IIS_IUSRS Full Control on the target folder

I’ve search around but not found anything that solved my issue, and there’s nothing helpfull in the EventLog or in the C:WindowsSystem32LogFilesHTTPERR folder

Could anyone tell me what’s wrong?

weir's user avatar

weir

4,5012 gold badges29 silver badges42 bronze badges

asked Nov 10, 2012 at 14:33

Andreas's user avatar

4

It could be that the user identity is outdated, especially if you’ve tried starting a stopped app pool and the next request again fails.

In IIS, go to the Application Pools under the Server, then find the correct Application Pool for your web site, and click on it. On the Advanced Settings menu to the right, select Identity and change it and enter new user and password. Click on your Application Pool again, and select Recycle to restart it.

You can also try looking at the error message in Event Viewer, under Windows Logs, Application, Details tab.

Broots Waymb's user avatar

Broots Waymb

4,7043 gold badges28 silver badges51 bronze badges

answered Oct 30, 2013 at 13:02

live-love's user avatar

live-lovelive-love

47.9k22 gold badges234 silver badges201 bronze badges

8

Other answers are fine. But in my case, I was working on a Windows box that already was running some old IIS, IISExpress or any other web site. What happened is urls ACLs where reserved somehow in the system. So, you might want to check this.

Here is the console command to dump all URL acls:

netsh http show urlacl

Check what’s returned here, and if anything matches the url you are testing, here is the command to delete one URL acl (for example):

netsh http delete urlacl url=http://localhost:2018/

(beware to carefully note what you do here in case it was not related to the original problem)

answered Jan 16, 2015 at 14:11

Simon Mourier's user avatar

Simon MourierSimon Mourier

131k21 gold badges245 silver badges295 bronze badges

5

In my case the problem was the DefaultAppPool. I changed the «Load User Profile» to false and now it works. However, I don’t know if there are side effects to this.

enter image description here

Further reading on setting the Load User Profile option: What exactly happens when I set LoadUserProfile of IIS pool?

TylerH's user avatar

TylerH

20.7k65 gold badges73 silver badges98 bronze badges

answered Apr 18, 2014 at 16:54

Juan Carlos Puerto's user avatar

2

Check your application’s respective Application Framework Pool — it could be stopped. If it is, start it and check again.

If you’re still experiencing issues you can also check out Event Viewer to find the cause of that error in order to troubleshoot more.

Robotnik's user avatar

Robotnik

3,6133 gold badges31 silver badges49 bronze badges

answered Oct 25, 2013 at 10:20

Scoolsam's user avatar

ScoolsamScoolsam

5714 silver badges3 bronze badges

1

If the app pool is running under some specific user identity, then go to the advanced settings and update the username and password again to ensure they are correct.

TylerH's user avatar

TylerH

20.7k65 gold badges73 silver badges98 bronze badges

answered Aug 16, 2013 at 15:17

Mahboob Alam's user avatar

0

If the app pool immediately stops after you start it and your event log shows:

The worker process for application pool ‘APP_POOL_NAME’ encountered an
error ‘Cannot read configuration file ‘ trying to read configuration
data from file ‘?’, line number ‘0’. The data field contains
the error code.

… you may experiencing a bug that was apparently introduced in the Windows 10 Fall Creators Update and/or .Net Framework v4.7.1. It can be resolved via the following workaround steps, which are from this answer to the related question Cannot read configuration file ‘ trying to read configuration data from file ‘\?<EMPTY>’, line number ‘0’.

  1. Go to the drive your IIS is installed on, eg. C:inetpubtempappPools
  2. Delete the directory (or virtual directory) with the same name as your app pool.
  3. Recycle/Start your app pool again.

I have reported this bug to Microsoft by creating the following issue on the dotnet GitHub repo: After installing 4.7.1, IIS AppPool stops with «Cannot read configuration file».

EDIT

Microsoft responded that this is a known issue with the Windows setup process for the Fall Creators Update and was documented in KB 4050891, Web applications return HTTP Error 503 and WAS event 5189 on Windows 10 Version 1709 (Fall Creators Update). That article provides the following workaround procedure, which is similar to the one above. However, note that it will recycle all app pools regardless of whether they are affected by the issue.

  1. Open a Windows PowerShell window by using the Run as administrator
    option.
  2. Run the following commands:
    • Stop-Service -Force WAS
    • Remove-Item -Recurse -Force C:inetpubtempappPools*
    • Start-Service W3SVC

answered Nov 27, 2017 at 15:33

weir's user avatar

weirweir

4,5012 gold badges29 silver badges42 bronze badges

1

Or if none of the current solutions work, look in your website’s directory for a file called app_offline.htm. That basically tells IIS that your site is unavailable and to show this page instead.

To fix it, either delete it or rename it to app_offline.htm.bak.

In my case, I added it while showing a colleague how to use that to prevent traffic to the site temporarily and then forgot that I did that on my box. Sigh.

answered Oct 15, 2015 at 14:50

Hallmanac's user avatar

HallmanacHallmanac

5292 gold badges8 silver badges14 bronze badges

0

Start by looking in Event Viewer, either under the System or the Application log.

In my case the problem was that no worker process could be started for the App Pool because its configuration file couldn’t be read — I had included an extra ‘.’ at the end of its name.

answered Mar 22, 2013 at 15:36

Samuel Jack's user avatar

Samuel JackSamuel Jack

32.6k16 gold badges116 silver badges155 bronze badges

It is possible that your domain requires the account used for running the AppPool to have batch logon rights. In which case you will see this same error message. The way you can tell if that is the case, is by looking at the System events in the Event Viewer. There should be an event saying that the account being used with the App Pool has either ‘the wrong password or does not have batch logon rights’.

This is why developers quite often use IIS Express on their development machine, since it by passes the batch logon rights issue.

answered Jan 30, 2013 at 14:56

Hashim Akhtar's user avatar

Hashim AkhtarHashim Akhtar

8052 gold badges11 silver badges16 bronze badges

For my case, My Default Application Pool was offline.

To troubleshoot the problem, I checked the IIS logs located in C:WindowsSystem32LogFileHTTPERR. Scroll down to the most recent error logs, this will show you problems with IIS if any.

My Error was «503 1 AppOffline DefaultPool»

Solution

  • Open IIS Manager
  • Click on Application Pools, this lists all application pool to your right.
  • Check if the application pools hosting your api or site has a stop sign on it. If so, right click the application pool and click start.
  • Try again to access your service from the client

Ryan M - Regenerate response's user avatar

answered Jun 22, 2018 at 14:54

mut tony's user avatar

mut tonymut tony

3577 silver badges9 bronze badges

I ran into the same issue, but it was an issue with the actual site settings in IIS.

Select Advanced Settings... for your site/application and then look at the Enabled Protocols value. For whatever reson the value was blank for my site and caused the following error:

HTTP Error 503. The service is unavailable.

The fix was to add in http and select OK. The site was then functional again.

answered Oct 17, 2013 at 20:31

atconway's user avatar

atconwayatconway

20.5k29 gold badges153 silver badges228 bronze badges

2

Check Event Viewer — Windows — Application. If there is a red Error line made from IIS-W3SVC-WP and the message is like The Module DLL C:Windowssystem32inetsrvrewrite.dll failed to load. The data is the error. then you are missing some Windows Setup features.

In Windows Server 2012 go to Server Manager, Add Roles and Features, Web Server (IIS) and add the matching feature. Usually, most of the Application Development section is installed. Here is a complete list of IIS features and their associated DLL to help in diagnosis.

After going through a few iterations of that I ended on the error message above regarding «rewrite.dll». This led to a direct download and install of Microsoft URL Rewrite tool. Finally all websites came to life.

answered Nov 10, 2014 at 19:25

SushiGuy's user avatar

SushiGuySushiGuy

1,56317 silver badges20 bronze badges

2

Our server ran out of disk space on Sunday afternoon which led to an application suddenly failing and returning HTTP error 502. The logs were empty so it had to be something that was occurring before IIS even did anything.

A swift look at the event viewer(WIN+R > eventvwr) exposed the issue.
enter image description here

It’s a good idea to filter out the output of the System and Application windows to WAS since it can get pretty verbose in there.

The application depended on another one which was disabled. Therefore keep in mind an application can go down indirectly if one of it’s dependent processes has gone down. We simply re-enabled the .NET application pool and our other application started running normally again.

answered Feb 27, 2017 at 17:05

Patrick.SE's user avatar

Patrick.SEPatrick.SE

4,4045 gold badges33 silver badges44 bronze badges

If you have IIS URL Rewriting installed it could be to do with that. I suffered issues after a Windows 10 Update.

This StackOverflow post helped me.

Go to Windows Control Panel > Programs and Features > IIS URL Rewrite Module 2 > Repair.

Community's user avatar

answered Apr 25, 2016 at 11:23

ᴍᴀᴛᴛ ʙᴀᴋᴇʀ's user avatar

ᴍᴀᴛᴛ ʙᴀᴋᴇʀᴍᴀᴛᴛ ʙᴀᴋᴇʀ

2,7341 gold badge26 silver badges38 bronze badges

1

In my case, the problem was that another application was using the port that I had bound to my web site.

I found it by running the following command from a command line, which lists all of the listening ports and the executable involved:

netstat -b

answered Mar 25, 2016 at 21:23

Avalanchis's user avatar

AvalanchisAvalanchis

4,5013 gold badges38 silver badges48 bronze badges

If you have McAfee HIPS and if you see the following error in event viewer application log:

The Module DLL C:WindowsSystem32inetsrvHipIISEngineStub.dll failed to load.
The data is the error.

Then this workaround on McAfee.com resolved the issue in my case.

Quote from the page:

  1. Click Start, Run, type explorer and click OK.
  2. Navigate to: %windir%system32inetsrvconfig
  3. Open the file applicationHost.config as Administrator for editing in Notepad.
  4. Edit the <globalModules> section and remove the following line:

    <add name=»MfeEngine» image=»%windir%System32inetsrvHipIISEngineStub.dll» />

  5. Edit the <modules> section and remove the following line:

    <add name=»MfeEngine» />

  6. After you have finished editing the applicationHost.config file, save the file, then restart the IIS server using iisreset or by restarting the system.

Stacked's user avatar

Stacked

6,7846 gold badges57 silver badges73 bronze badges

answered Dec 28, 2014 at 15:01

Orhan Celik's user avatar

Orhan CelikOrhan Celik

1,50315 silver badges12 bronze badges

0

Actually, in my case https://localhost was working, but http://localhost gave a HTTP 503 Internal server error. Changing the Binding of Default Web Site in IIS to use the hostname localhost instead of a blank host name.

IIS Site bindings for HTTPtname for http binding

answered Aug 30, 2018 at 14:58

Tore Aurstad's user avatar

Tore AurstadTore Aurstad

3,0321 gold badge25 silver badges21 bronze badges

This could also happen if any recent installs or updates happened with .NET framework and/or ASP.NET. If you are unsure of what happened recently and if all your apps use ASP.NET version 4, you can try reset them by running the following commands in command prompt in administrator mode.

cd C:WindowsMicrosoft.NETFramework64v4.0.30319
aspnet_regiis -i

This makes sure to install or reinstall ASP.NET 4 and updates existing applications to use ASP.NET 4 version of the app pool. It updates both IIS Classic and Integrated mode handlers and script mappings in the IIS metabase. It also recreates ASP.NET v4.0 and ASP.NET v4.0 Classic app pools, and sets .NET framework 4 to DefaultAppPool and Classic .NET app pools.

answered Mar 31, 2016 at 15:59

Prabu Arumugam's user avatar

Prabu ArumugamPrabu Arumugam

1,9292 gold badges15 silver badges19 bronze badges

I changed the port from 80 to 8080, that’s why this error occur. I write localhost/ in search bar then this error occur. My problem is resolved by writing localhost:8080/ in the search then local host open.

answered Aug 1, 2019 at 5:22

ABDUL KHALIQ's user avatar

1

This happened to me on a server on our intranet. After browsing through blog posts and Windows logs, it turned out that a few days before Christmas 2015 (related to a Windows Update?) my web site application pool wanted to create a config file in folder c:inetpubtempappPools, but access to this folder was restricted. This caused the application pool to be disabled.

After adding Full control to Everyone on this temp folder, I restarted the Windows Process Activation Service and everything went online again.

If I’d been a little more elegant, it would probably had been enough to grant the AppPool user full control to the folder, but I never seem to remember how the app pool name and app pool user relates to eachother…

answered Jan 20, 2016 at 15:41

Daniel Persson's user avatar

Daniel PerssonDaniel Persson

2,1711 gold badge17 silver badges24 bronze badges

Same thing with IIS Express 10.0 after upgrading Windows 7 to Windows 10.
Solution: go to IIS and enable all disabled websites and reinstall ASP.NET Core.

answered Jul 22, 2016 at 11:14

1_bug's user avatar

1_bug1_bug

5,4054 gold badges50 silver badges58 bronze badges

Also check the address bar and make sure the page is in the right location.

This error can be returned instead of the 404 (Page not found). In my case, it was a bad link on the page that didn’t have a subfolder included.

answered Dec 3, 2015 at 21:15

Tony L.'s user avatar

Tony L.Tony L.

17.3k8 gold badges68 silver badges65 bronze badges

I was having this problem when cleaning up my IIS on dev machine, and I had somehow created a virtual folder for a subfolder of my actual development web that I couldn’t clear and was creating conflicts.

To clear it I had to use

C:WindowsSystem32inetsrvappcmd.exe list vdir

and then individually remove the problem virtual directories using

C:WindowsSystem32inetsrvappcmd.exe delete app /app.name:"Default Web Site"/{name of virtual directory}

answered Dec 2, 2019 at 10:23

Siemsen's user avatar

SiemsenSiemsen

1991 gold badge3 silver badges13 bronze badges

enter image description here

For me the solution is to change Enable 32-bit Applications to False


None of the answers worked for me. So I’d like to share what I found after hours of research..

Keep seeing this message from event logs: The Module DLL C:Windowssystem32RpcProxyRpcProxy.dll failed to load. The data is the error. Turns out that dll is 64bit and cannot be loaded into 32bit process.

answered Nov 10, 2020 at 15:44

Rohim Chou's user avatar

Rohim ChouRohim Chou

82710 silver badges16 bronze badges

You can also try the following.

Right-click on the site and ‘Basic Settings…’
Click on ‘Connect As…’
Click on Specific User and give the new credentials.

Now it should work.

answered Feb 19, 2021 at 9:57

Tushar Wason's user avatar

In my case, I had to change my userPass of network because company policies. So, you need to edit your AppPool:
click on Application Pools. Select your pool, ‘advanced Settings…’ go to ‘Process Model’ click on ‘Identity’ and Click on Specific User and give the new credentials.

Dharman's user avatar

Dharman

30.4k22 gold badges84 silver badges133 bronze badges

answered Apr 7, 2021 at 8:40

RogerEdward's user avatar

This might be because of number of connections to the database. I had such a situation and so, wrote a de-constructor and killed db open connection and it resolved.

answered Feb 27, 2014 at 12:34

user3225121's user avatar

1

In our role as Web support engineers, we resolve and prevent service errors in both Linux and Windows servers. Recently we were contacted by a Windows server owner who was getting “HTTP Error 503. The service is unavailable” in his websites.

Upon examining the EventViewer logs, we could see the error “A process serving application pool ‘plesk(default)(4.0)(pool)’ suffered a fatal communication error with the Windows Process Activation Service”.

See how we help web hosting companies

Today we’ll see what causes IIS “HTTP Error 503. The service is unavailable.” error and how we resolved it.

Our Windows server experts noted that all the domains in the server were using the same application pool [ie. ‘plesk(default)(4.0)(pool)’]. In our experience handling such errors, the following causes have been noted for this error.

  1. Application Pool of the corresponding Wep Application is Stopped – In an IIS server, the domains are assigned to application pools, some dedicated and some shared. If the associated application pool for a domain is in stopped or disabled state, it would cause the website to show “HTTP Error 503. The service is unavailable.” message.
  2. Any misconfiguration in the application pool or site settings, such as spawning applications in 32-bit mode, that can tamper with its proper functioning, can cause error in the site. Improper IIS configuration have noted to cause the worker process to fail. Process crashes also happen due to incorrect application logic. In some cases, the web server protocol may not be enabled in the site settings, and the site can show up ‘HTTP Error 503.’
  3. Issues related to the user Identity of application Pool – An application pool is associated with a user identity, which allows you to run that application pool under a unique account. This user account can get locked at times, can have its password expired, or may not have adequate privileges to run the application pool. Any of these issues can tamper with the website functioning.
  4. Application pool running out of RAM or other server resources, causing it to crash, often lead to ‘HTTP Error 503.’
  5. Server migrations have also seen to have caused such errors in the website, if the IIS configuration settings of two servers are not compatible with each other, which can affect domain performance.

[ You don’t have to lose your sleep over server errors. Our expert server support specialists monitor & maintain your servers 24/7/365 and keep them rock solid. ]

How to resolve IIS “HTTP Error 503. The service is unavailable.” error

To pinpoint the actual cause of the 503 error, we examine the System event logs, which gives a hint towards what is the reason for the error. Based on that, we follow various debugging methods to resolve it.

If the error is due to a stopped application pool, then usually starting it would resolve the issue. From the IIS Manager -> Application Pools node, right click on the DefaultAppPool to check the status.

On noticing that the service is stopped, we start it. If the service is running, we try restarting it and the error would be gone. But in most cases, the fix may not be as simple as that.

In cases where the application pool crashes frequently, restarting it all the time is not the right way to fix it. We monitor the server and debug further into what is causing the application pool to crash.

For websites that are resource-intense, it is always better to assign a dedicated application pool for that domain. Another aspect we check and fix the settings of application pool and site, such as enabling the relevant protocol.

One of the key issues many fail to notice, is the user identity settings. We check the account settings and password of the identity and confirm that it is working fine. If mismatch noted, we would update the settings.

However, in this specific scenario, the issue was due to inadequate permissions of the application to run, which caused the error. By reconfiguring the application pool to run with a higher privileged identity, we were able to resolve the issue.

To avoid resource crunch leading to application crashes, we also optimized the IIS server and could see improvement in the capacity to handle connections with lesser CPU usage.

Use your time to build your business. We’ll take care of your servers. Hire Our server experts to resolve and prevent server issues. ]

At Bobcares, our 24/7 Support Engineers constantly monitor all the services in the server and proactively audit the server for any errors or corruption in them.

With our systematic debugging approach for service or other software errors, we have been able to provide an exciting support experience to the customers.

If you would like to know how to avoid downtime for your customers due to errors or other service failures, we would be happy to talk to you.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure./p>

SEE SERVER ADMIN PLANS

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

  • Remove From My Forums
  • Question

  • User1057034050 posted

    Hi,

    I’ve got the famous «HTTP Error 503. The service is unavailable.» when I try to access to localhost on my computer. (it doesn’t work neither with
    http://127.0.0.1).

    Googling has provided lots of near hits, but no solution have worked (application pools are started and a IIS reinstall changed nothing)

    I have followed this steps (http://mvolo.com/where-did-my-iis7-server-go-troubleshooting-503-quotservice-unavailablequot-errors) but I haven’t an IIS-W3SVC-WP error.

    I have also changed my computer name (who contained some underscore) after read this post (http://forums.iis.net/p/1183845/2005559.aspx) without results. By despite I have restore system to factory default (with Acer Erecovery Management) but the problem
    still persist after a re-installation.

    I’m gonna go crazy… have you an idea ?

    Thanks.

Answers

  • User-2064283741 posted

    Ummh HTTP API 503 errors with a reason code of N/A are not common.

    MS documentation gives:

    N/A

    A service unavailable error occurred (HTTP error 503). The service is unavailable as a result of an internal error such as a memory allocation failure.

    Now it could be that the IPv6 you are using is failing and/or misconfiguration in some way. I would check this site using good old IPv4 and if there is any difference in behaviour.

    • Marked as answer by

      Tuesday, September 28, 2021 12:00 AM

Понравилась статья? Поделить с друзьями:
  • Ошибка 503 service temporarily unavailable что это значит
  • Ошибка 503 service temporarily unavailable как исправить
  • Ошибка 503 service temporarily unavailable nginx
  • Ошибка 503 nginx что это
  • Ошибка 503 bad gateway что это значит