- How to: Install and uninstall Windows services
- Install using InstallUtil.exe utility
- Uninstall using InstallUtil.exe utility
- Install using PowerShell
- Uninstall using PowerShell
- Как установить программу в качестве службы
- Установка программы в качестве службы
- Удаление службы
- Практическое руководство. Установка и удаление служб Windows How to: Install and uninstall Windows services
- Установка с помощью программы InstallUtil.exe Install using InstallUtil.exe utility
- Удаление с помощью служебной программы InstallUtil.exe Uninstall using InstallUtil.exe utility
- Установка с помощью PowerShell Install using PowerShell
- Удаление с помощью PowerShell Uninstall using PowerShell
- Add nginx.exe as Windows system service (like Apache)?
- 9 Answers 9
- start.bat
- stop.bat
How to: Install and uninstall Windows services
If you’re developing a Windows service with the .NET Framework, you can quickly install your service app by using the InstallUtil.exe command-line utility or PowerShell. Developers who want to release a Windows service that users can install and uninstall can use the free WiX Toolset or commercial tools like Advanced Installer, InstallShield, or others. For more information, see Create an installer package (Windows desktop).
If you want to uninstall a service from your computer, don’t follow the steps in this article. Instead, find out which program or software package installed the service, and then choose Apps in Settings to uninstall that program. Note that many services are integral parts of Windows; if you remove them, you might cause system instability.
To use the steps in this article, you first need to add a service installer to your Windows service. For more information, see Walkthrough: Creating a Windows service app.
You can’t run Windows service projects directly from the Visual Studio development environment by pressing F5. Before you can run the project, you must install the service in the project.
You can use Server Explorer to verify that you’ve installed or uninstalled your service.
Install using InstallUtil.exe utility
From the Start menu, select the Visual Studio directory, then select Developer Command Prompt for VS .
The Developer Command Prompt for Visual Studio appears.
Access the directory where your project’s compiled executable file is located.
Run InstallUtil.exe from the command prompt with your project’s executable as a parameter:
If you’re using the Developer Command Prompt for Visual Studio, InstallUtil.exe should be on the system path. Otherwise, you can add it to the path, or use the fully qualified path to invoke it. This tool is installed with the .NET Framework in %WINDIR%\Microsoft.NET\Framework[64]\ .
- For the 32-bit version of the .NET Framework 4 or 4.5 and later, if your Windows installation directory is C:\Windows, the default path is C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe.
- For the 64-bit version of the .NET Framework 4 or 4.5 and later, the default path is C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe.
Uninstall using InstallUtil.exe utility
From the Start menu, select the Visual Studio directory, then select Developer Command Prompt for VS .
The Developer Command Prompt for Visual Studio appears.
Run InstallUtil.exe from the command prompt with your project’s output as a parameter:
After the executable for a service is deleted, the service might still be present in the registry. If that’s the case, use the command sc delete to remove the entry for the service from the registry.
Install using PowerShell
From the Start menu, select the Windows PowerShell directory, then select Windows PowerShell.
Access the directory where your project’s compiled executable file is located.
Run the New-Service cmdlet with the with your project’s output and a service name as parameters:
Uninstall using PowerShell
From the Start menu, select the Windows PowerShell directory, then select Windows PowerShell.
Run the Remove-Service cmdlet with the name of your service as parameter:
After the executable for a service is deleted, the service might still be present in the registry. If that’s the case, use the command sc delete to remove the entry for the service from the registry.
Как установить программу в качестве службы
Наверняка, многие сталкивались с ситуацией, когда есть необходимость запускать программу до входа пользователя в систему, но в установщике программы нет опции «Установить в качестве службы».
Установка программы в качестве службы
Первые 4 пункта понадобятся лишь в windows 8.1
1 Вызовите боковую панель Windows 8.1. Для этого можно использовать комбинацию клавиш WIN+C.
2 Выберите Поиск:
3 В поле поиска введите командная строка. В списке появится позиция Командная строка с системной иконкой.
Нажмите по ней правой кнопкой мыши:
4 Выберите Запуск от имени администратора:
5 Нажмите Да:
6 В командной строке введите путь к программе, которую вы хотите установить в качестве службы, с ключом /installservice и нажать ENTER. Путь необходимо взять в кавычки.
После нажатия на ENTER ответьте «Да» на запрос службы контроля учётных записей:
7 Если программа запросит учётные данные для запуска, как в нашем примере, введите реквизиты учётной записи администратора и нажмите ОК:
Далее, программа, которую вы установили в качестве службы, сообщит вам об успешной установке службы.
У каждой программы это окно будет разным
Зайдите в службы (Выполнить — services.mcs — ENTER) и проверьте, что в списке присутствует только что установленная служба:
Удаление службы
Процедура удаления службы схожа с установкой. Отличие лишь в том, что после пути к программе нужно указать ключ /uninstallservice.
Практическое руководство. Установка и удаление служб Windows How to: Install and uninstall Windows services
Если вы разрабатываете службу Windows с помощью .NET Framework, вы можете быстро установить приложение службы с помощью служебной программы командной строки InstallUtil.exe или PowerShell. If you’re developing a Windows service with the .NET Framework, you can quickly install your service app by using the InstallUtil.exe command-line utility or PowerShell. Если вы являетесь разработчиком и хотите создать службу Windows, которую пользователи могут устанавливать и удалять, можно использовать набор инструментов WiX или коммерческие средства, такие как Advanced Installer, InstallShield или другие. Developers who want to release a Windows service that users can install and uninstall can use the free WiX Toolset or commercial tools like Advanced Installer, InstallShield, or others. См. сведения о создании пакета установщика (классическое приложение Windows). For more information, see Create an installer package (Windows desktop).
Если вы хотите удалить службу на своем компьютере, не выполняйте процедуру, описанную в этой статье. If you want to uninstall a service from your computer, don’t follow the steps in this article. Вместо этого определите, какая программа (или программный пакет) установила эту службу, а затем выберите Приложения в параметрах, чтобы удалить эту программу. Instead, find out which program or software package installed the service, and then choose Apps in Settings to uninstall that program. Следует отметить, что многие службы являются составной частью ОС Windows. Если их удалить, это может привести к нестабильной работе системы. Note that many services are integral parts of Windows; if you remove them, you might cause system instability.
Чтобы использовать процедуру, описанную в этой статье, сначала необходимо добавить установщик службы в свою службу Windows. To use the steps in this article, you first need to add a service installer to your Windows service. Дополнительные сведения см. в разделе Пошаговое руководство: создание диспетчера служб Windows. For more information, see Walkthrough: Creating a Windows service app.
Проекты служб Windows нельзя запускать непосредственно из среды разработки Visual Studio путем нажатия клавиши F5. You can’t run Windows service projects directly from the Visual Studio development environment by pressing F5. Перед запуском проекта необходимо установить службу в проекте. Before you can run the project, you must install the service in the project.
Запустите обозреватель сервера и убедитесь, что служба установлена или удалена. You can use Server Explorer to verify that you’ve installed or uninstalled your service.
Установка с помощью программы InstallUtil.exe Install using InstallUtil.exe utility
В меню Пуск выберите каталог Visual Studio и затем Командная строка разработчика для VS . From the Start menu, select the Visual Studio directory, then select Developer Command Prompt for VS .
Появится командная строка разработчика для Visual Studio. The Developer Command Prompt for Visual Studio appears.
Откройте каталог, где находится скомпилированный исполняемый файл вашего проекта. Access the directory where your project’s compiled executable file is located.
Запустите InstallUtil.exe из командной строки, указав исполняемый файл проекта в качестве параметра: Run InstallUtil.exe from the command prompt with your project’s executable as a parameter:
Если вы используете командную строку разработчика для Visual Studio, системный путь должен указывать на файл InstallUtil.exe. If you’re using the Developer Command Prompt for Visual Studio, InstallUtil.exe should be on the system path. Если это не так, можно добавить его в путь или использовать полный путь для его вызова. Otherwise, you can add it to the path, or use the fully qualified path to invoke it. Этот инструмент устанавливается вместе с платформой .NET Framework в папку %WINDIR%\Microsoft.NET\Framework[64]\ . This tool is installed with the .NET Framework in %WINDIR%\Microsoft.NET\Framework[64]\ .
Пример: For example:
- Для 32-разрядной версии .NET Framework 4 или 4.5 и более поздних версий: если каталог установки Windows — C:\Windows, по умолчанию используется путь C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe. For the 32-bit version of the .NET Framework 4 or 4.5 and later, if your Windows installation directory is C:\Windows, the default path is C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe.
- Для 64-разрядной версии .NET Framework 4 или 4.5 и более поздних версий: по умолчанию используется путь C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe. For the 64-bit version of the .NET Framework 4 or 4.5 and later, the default path is C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe.
Удаление с помощью служебной программы InstallUtil.exe Uninstall using InstallUtil.exe utility
В меню Пуск выберите каталог Visual Studio и затем Командная строка разработчика для VS . From the Start menu, select the Visual Studio directory, then select Developer Command Prompt for VS .
Появится командная строка разработчика для Visual Studio. The Developer Command Prompt for Visual Studio appears.
Запустите InstallUtil.exe из командной строки, указав выходные данные проекта в качестве параметра: Run InstallUtil.exe from the command prompt with your project’s output as a parameter:
После удаления исполняемого файла для службы сама служба может по-прежнему присутствовать в реестре. After the executable for a service is deleted, the service might still be present in the registry. В этом случае удалить запись службы из реестра можно с помощью команды sc delete. If that’s the case, use the command sc delete to remove the entry for the service from the registry.
Установка с помощью PowerShell Install using PowerShell
В меню Пуск выберите Каталог Windows PowerShell и Windows PowerShell. From the Start menu, select the Windows PowerShell directory, then select Windows PowerShell.
Откройте каталог, где находится скомпилированный исполняемый файл вашего проекта. Access the directory where your project’s compiled executable file is located.
Выполните командлет New-Service, указав в качестве параметров выходные данные проекта и имя службы. Run the New-Service cmdlet with the with your project’s output and a service name as parameters:
Удаление с помощью PowerShell Uninstall using PowerShell
В меню Пуск выберите Каталог Windows PowerShell и Windows PowerShell. From the Start menu, select the Windows PowerShell directory, then select Windows PowerShell.
Выполните командлет Remove-Service, указав в качестве параметра имя службы. Run the Remove-Service cmdlet with the name of your service as parameter:
После удаления исполняемого файла для службы сама служба может по-прежнему присутствовать в реестре. After the executable for a service is deleted, the service might still be present in the registry. В этом случае удалить запись службы из реестра можно с помощью команды sc delete. If that’s the case, use the command sc delete to remove the entry for the service from the registry.
Add nginx.exe as Windows system service (like Apache)?
I set up NGINX as a front end server for static content and I use Apache as a back-end server for other thing.
The thing is I can’t find a logical answer that allows me to make nginx.exe a Windows system service (like my Apache).
Any come across an answer to this?
9 Answers 9
How to do it with Windows Service Wrapper
(Note: There are easier alternatives by now — see also solutions described here below using chocolatey package manager by suneg and using NSSM directly from Adamy)
- Download the latest version of Windows Service Wrapper via github or nuget.
- Current version as of this writing is v2.2.0
- Since v2.x executables for .NET2.0 and .NET4.0 are available — others only on demand.
- Rename winsw-*.exe to something like nginxservice.exe .
- This is the name that will show up for the process that owns your nginx process.
Place an XML file next to the exe with the same base name, e.g. nginxservice.xml . The contents should be like below (verify your nginx location).
- You can find up to date details about the configuration on the config github page, a generic example showing all possible options here and an installation guide.
You will now have an nginx service in your Services! (It is set to start automatically on boot; if you want to start your server, you must manually start the service ( net start nginx ).)
Additional info not contained in above blog post:
You can find the latest version of the Windows Service Wrapper also via this Maven Repository: http://repo.jenkins-ci.org
Examples for Maven + Gradle:
Download NSSM form http://nssm.cc/download . «Run %NSSM_HOME%\nssm.exe install “Nginx”»
Select the Nginx executable in the NSSM dialog, then OK. Go to Services and start the new created service «Nginx», done.
1\nginx & nginx.exe -s reload and run this bat through psexec . – andrej Jun 5 ’20 at 9:00
SC.EXE will only work for executables that already support the Windows Services API and can respond properly to start and stop requests from the Services Control Manager (SCM). Other regular applications, not specifically written as a service, will simply fail to start (usually with error 1053).
For those exe’s, you need a «service wrapper» — a small utility that can accept the start/stop commands from the SCM and run/terminate your application accordingly. Microsoft provides Srvany (which is free yet very basic), but there are several other free and commercial alternatives.
BTW, you should check out this guide showing how to run Nginix as a service, especially step 7 which discusses how to stop Nginix properly. Not every wrapper will support that functionality (Srvany doesn’t).
You can using start.bat and stop.bat to realize the same effect.
start.bat
stop.bat
The easiest way I’ve found, was using the Chocolatey package manager.
Once Chocolatey is installed, you open an administrative prompt and type:
You now have a Windows service named ‘nginx’ running.
Download zip file from here.
Extract nginx-service.exe from winginx\build and run it.
Official nginx wiki referes on winginx for this purpose. It builds exe-installer in linux environment. Process looks like this:
To get actual versions you should specify them in Makefile .
NSSM is the best tool to run Nginx as a service.
If you do not want to use any external 3rd party software then you can implement any of these two methods.
- Windows Task Scheduler
- Windows startup shortcut
Windows Task Scheduler
- As mentioned in this answer prepare one start.bat file.
- Put this file where nginx.exe is present.
- Open windows task scheduler and set up the task as described in this answer to run it indefinitely.
- Do not forget to run this task as the highest privilege with the system account, more details can be found here.
- Make the task to start daily at a certain time, through the bat file it will check whether the service is already running to avoid creating multiple nginx.exe instances.
- If due to some reason Nginx shuts down, within 5 minutes it will start.
Windows Startup shortcut
Create one shortcut of nginx.exe and put it in the startup folder of Windows.
Follow this answer to find your startup location.