Как изменить порт экземпляра Microsoft SQL Server?
09.07.2020
insci
SQL Server
Комментариев пока нет
В этой статье мы разберемся как узнать текущий TCP порт, на котором слушает и ожидает подключения именованный или default экземпляр MS SQL Server, как изменить порт подключения SQL Server на статический/динамический и как используется служба SQL Server Browser клиентами при подключении к SQL.
- Default экземпляр SQL Server (MSSQLSERVER) работает на статическом порту TCP 1433. Именно к этому порту подключаются клиенты, или консоль SQL Server Management Studio (SSMS);
- Именованные экземпляры MSSQL и SQL Server Compact по-умолчанию настроены на использование динамического TCP порта из диапазона RPC (49152 – 65535).
Динамической порт означает, что номер порта, на котором принимает подключение экземпляр MSSQL назначается при запуске службы SQL Server. В большинстве случаев, даже после перезагрузки сервера, SQL Server начнет слушать тот же самый динамический TCP порт, который был назначен до перезагрузки. Но если этот порт занят, SQL Server запустится на новом порту TCP (приложение, которое использует SQL обычно без проблем получит номер нового порта от службы SQL Server Browser, об этом чуть ниже). Динамический порты SQLServer удобны с точки зрения простоты администрирования нескольких экземпляров SQL на одном сервере, но вызывают множество проблем, если в вашей сети используются межсетевые экраны.
Изменение номера TCP порта экземпляра SQL Server
Вы можете перенастроить ваш сервер так, чтобы он слушал на другом статическом TCP или динамическом порту. Как правило это нужно, когда на одном SQL Server-e запушено несколько экземпляров, или у вас используются межсетевые экраны.
Для управления портами подключения нам потребуется SQL Server Configuration Manager. Обычно эта оснастка устанавливается вместе с экземпляром MSSQL.
Запустите SQL Server Configuration Manager и разверните секцию SQL Server Network Configuration.
В моём случае на сервере установлен всего 1 экземпляр MSSQL– NODE1, поэтому настраивать порты я буду для него. В списке доступных протоколов для данного экземпляра имеются:
- Протокол Shared Memory используется для подключения с локального компьютера (с того, где установлен экземпляр MSSQL). Отключать его не рекомендуется;
- Named Pipes может использоваться по протоколу TCP/IP, но его использования не несёт особой выгоды, поэтому оставим его выключенным;
- TCP/IP – именно здесь настраиваются сетевые параметры MSSQL.

Щелкните дважды по TCP/IP.

На вкладке Protocol всего 3 параметра:
- Enabled – убедитесь, что протокол TCP/IP включен;
- Keep Alive – частота проверки того, что соединение еще актуально (в миллисекундах). Не меняйте этот параметр без необходимости;
- Listen All – неочевидная настройка, которая отвечает за секцию IPAll во вкладке IP Addresses. Если Listen All выставлена в No, то секция IPAll будет игнорироваться.
На вкладке IP Addresses вы увидите перечисление всех IP адресов машины (включая IPv6 и локальные) и соответствующие им настройки. Здесь вы можете задать разные TCP порты для локального и внешнего адреса подключения, или разные порты для разных внешних адресов (если у вас сервер с несколькими сетевыми интерфейсами в разных сегментах).

Скорее всего вы захотите изменить порт сразу для всех IP, поэтому нужно изменить его секции IPAll.

Параметр TCP Dynamic Ports отвечает за использование динамических портов.
- Пустое значение TCP Dynamic Ports отключает использование динамических портов SQL Server;
- 0 включает использование динамических TCP портовиз диапазона RPC 49152 – 65535;
- Выставлять здесь конкретное значение не имеет смысла – оно меняется каждый раз при перезагрузке экземпляра MSSQL.
Чтобы установить статический TCP порт для данного экземпляра SQL Server, отключите TCP Dynamic Ports, и задайте новый номер статического порта в параметре TCP Port.

Для применения изменений перезапустите службу SQL Server. Обратите внимание на отключенную службу SQL Server Browser.

Проверьте, что теперь к вашему экземпляру SQL можно подключиться через SSMS. Формат строки подключения такой:

Подключиться без указания порта не получится, поскольку SQL Browser выключен.
TCP порты и служба SQL Server Browser
До версии MSSQL 2000 нельзя было установить больше одного экземпляра СУБД на один компьютер. Такая возможность появилась в более новых версиях MSSQL. Служба SQL Server Browser впервые появилась в SQL Server 2005 и использовалась как посредник для распределения подключений между различными экземплярами MSSQL, установленными на одном компьютере.
Также SQL Server Browser отвечает за подключение к MSSQL (например, из SQL Server Management Studio) без указания порта, например testnode1\node1 . Служба SQL Server Browser узнает номер текущего динамического порта экземпляра из реестра и сообщает его клиенту.
Если вы отключите службу SQL Server Browser, то для подключения к экземпляру необходимо вручную указывать TCP порт. Например, testnode1\node1, 1440 .
При отключенной службе SQL Server Browser и использовании динамических портов приложения не смогут узнать номер порта, к которому нужно обращаться.
Стандартные порты SQL Server
- TCP 1433 — Стандартный порт SQL Server
- UDP 1433 – порт, используемый SQL Server Browser
Другие порты настраиваются при установке/настройке конкретного сервиса. Так что по умолчанию, Вам достаточно открыть в файерволе только два порта: 1433 TCP/UDP.
Если у вас используются строгие настройки фаервола, или если вы хотите максимально ограничить SQL Server, рекомендуется отключить Dynamic Ports (выставить пустое значение) и отключить службу SQL Server Browser.
Если же ваши SQL Server’a находятся в публичном доступе, то будет хорошей идеей поменять порт на нестандартный. Это не защитит от атак полностью, но снизит их число.
Предыдущая статья Следующая статья
Identify SQL Server TCP IP port being used
How do I find out what TCP/IP port SQL Server is using for a specific SQL Server instance? In this tip we look at different ways a database administrator can identify the port used by instance of SQL Server.
Solution
You probably know that by default, the SQL Server Database Engine listens on port 1433 for TCP/IP connections and port 1434 is used for UDP connections. However, if you have more than one instance of SQL Server running on the same server or if you have changed the default port then it may be difficult to know the port used by the database engine.
In this tip we will take a look at three different ways you can identify the port used by an instance of SQL Server.
- Reading SQL Server Error Logs
- Using SQL Server Configuration Manager
- Using Windows Application Event Viewer
Let’s take a look at each of the above options in detail.
1 — Identify Port used by Named Instance of SQL Server Database Engine by Reading SQL Server Error Logs
The SQL Server Error Log is a great place to find information about what is happening on your database server. The SQL Server Error Log records information with respect to the port in which an instance of the SQL Server Database Engine is listening. You can execute the below TSQL command which uses the XP_READERRORLOG extended stored procedure to read the SQL Server Error Log to find the port the SQL Server Database Engine is listening.

XP_READERRRORLOG
The parameters you can use with XP_READERRRORLOG are mentioned below for your reference:
- Value of error log file you want to read: 0 = current, 1 = Archive #1, 2 = Archive #2, etc.
- Log file type: 1 or NULL = error log, 2 = SQL Agent log
- Search string 1: String one you want to search for
- Search string 2: String two you want to search for to further refine the results
- Search from start time
- Search to end time
- Sort order for results: N’asc’ = ascending, N’desc’ = descending
By default, there are six archived SQL Server Error Logs along with the ERRORLOG which is currently used. However, it is a Best Practice to increase the number of SQL Server Error Logs from the default value of six. Hence I recommend that you read this tip Increase the Number of SQL Server Error Logs.
If you use sp_cycle_errorlog to cycle the SQL Server Error Logs you will need to look in the archive files to find the port information, because this is only stored in the startup error log.
Also, if you are using endpoints, such as Database Mirroring these will show up as ports as well. The way to differentiate the ports being used is to look at the data where the ProcessInfo column equals ‘Server’ to find the port used for the database engine.
2 — Identify Port used by SQL Server Database Engine Using SQL Server Configuration Manager
1. Open SQL Server Configuration Manager
2. In SQL Server Configuration Manager, expand SQL Server Network Configuration and then select Protocols for <instance name> on the left panel. To identify the TCP/IP Port used by the SQL Server Instance, right click on TCP/IP and select Properties from the drop down as shown below.

3. In TCP/IP Properties window click on the IP Addresses tab and you will see the Port used by the instance of SQL Server in either TCP Dynamic Ports for a dynamic port or TCP Port for a static port as highlighted in the snippet below.

3 — Identify Port used by SQL Server Database Engine Using Application Event Viewer
1. Open Event Viewer, Computer Management or Server Manager (to find Event Viewer)
2. Under Event Viewer, expand Windows Logs and then select Application on the left side panel. In the right panel you need to filter for events with Event ID 26022 as shown in the below snippet. To set a filter right click on Application and select Filter Current Log.

3. To view the Port Number double click an event and you can see the event properties as shown below. In this case, the named instance of SQL Server is listening on Port 57319. Note: you should look for the following Event «Server is listening on [ ‘any’ <ipv4> PortNumber]» in the event viewer. Also, if you have endpoints setup like Database Mirroring these will show up under EventID 26022 as well, so it gets a little harder to tell using this method.
Как узнать порт sql server
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
I have SQL Server 2008 R2 installed and also when I installed the demo version of our applications, it installed SQL Server 2005 Express. I set the SQL Server Express 2005 to not run automatically.
I want to find out which port my SQL Server 2008 R2 is installed.
How can I find it out?
Thanks in advance.
Premature optimization is the root of all evil in programming. (c) by Donald Knuth
Naomi Nosonovsky, Sr. Programmer-Analyst
Answers
Check the registry key
the registry entry will be: HKLM\Software\Microsoft\Microsoft SQL Server\<name of the instance>\MSSQLServer\SuperSocketNetLib\TCP
Check this knowledgebase article
- Marked as answer by Naomi N Wednesday, September 21, 2011 12:16 PM
- Marked as answer by Naomi N Wednesday, September 21, 2011 12:17 PM
You can run this code to get the port number, just update the value for @InstName variable to the name of the instance
- Marked as answer by Naomi N Wednesday, September 21, 2011 2:35 AM
Registry entires sometimes specific to SQL Server version so it canbe tricky
some other approaches to find port number
a) using SQL Server configuration manager
Launch SQL Server Configuration Manager
Start—>Run—>SQLServerManager10.msc
click on Protocols for <yourSQLServerInstance>
Right click on TCP/IP (Properties)
Under IP address tab, there is a TCP port listed
b) or Checking Windows Event log
you can check your Windows Appilcation event Log, when SQL Server restart there is an entry that shows which port number your SQL Server is listerning to
Overview of SQL Server Ports

This article is useful for a beginner in SQL Server administration and gives insights about the SQL Server Ports, the methods to identify currently configured ports.
Introduction
We can define the port as an endpoint of service for communication purposes. It might bind to a particular application or service. Once we install SQL Server, it configures default ports for SQL Server services. Each client application uses the combination of IP addresses and port number to connect to SQL Server.
We can have two kinds of SQL Server Ports in SQL Server.
- Static Port: A static port is always bound to a service or application. It does not change due to a service or system restart. By default, SQL Server uses static TCP port number 1433 for the default instance MSSQLSERVER. If you configure SQL Server to use a static port other than the default port, you should communicate it to the clients or application owners to specify in the connection string
- Dynamic Port: You can configure SQL Server to use a dynamic port. If you use dynamic port allocation, you specify port number zero in the network configuration. Once SQL Service restarts, it requests a free port number from the operating system and assigns that port to SQL Server.
As you know, Application uses a combination of SQL Server IP address and port number, you might think of a question – How will an application know the port number for connecting to SQL Server?
Once the operating system allocates a dynamic SQL Server Port to SQL Server, it writes that port number in the Windows registry. SQL Server Browser service uses UDP static port 1434. It reads the registry for the assigned TCP port. SQL Server client library connects and sends a UDP message using port 1434. SQL Server Browser service gives back the port number of a specific instance. An application can connect to SQL Server using that dynamic SQL Server port. SQL Server default instance uses the static port; therefore, SQL Server Browser does not return port for the default instance.
In most of the cases, SQL Server uses the same dynamic the SQL Server Port upon restart of the SQL Service as well. Suppose you stopped SQL Services and operating system allocated the dynamic port number (previously assigned to SQL) to another service, SQL Server gets another dynamic port assigned to it.
SQL Browser service is essential for the named instances with dynamic port allocation. It should be in running status for application to query and get the port details.
Check SQL Server Port Number
In this section, we will check a different method to check for the SQL Server Port number.
Method 1: SQL Server Configuration Manager:
It is the most common method to find the SQL Server Port number.
-
Step 1:
Open SQL Server Configuration Manager from the start menu. In case you have multiple SQL Server versions you might get an error message while opening SQL Server Configuration Manager:
Cannot connect to WMI provider. You do not have permission or the server is unreachable
In order to fix it, open the administrative command prompt and execute the following command