17.2. Установка Postgres Pro Enterprise в Windows
Postgres Pro предлагает следующие режимы установки в поддерживаемых системах Windows:
Установка в графическом режиме с помощью интерактивного мастера
Вы также можете настроить среду для использования процедурных языков PL/Perl и PL/Python, если они требуются для ваших целей. За подробностями обратитесь к Подразделу 17.2.4.
Во избежание недопонимания учтите, что в системах Windows имеются следующие отдельные пользователи:
Установка Postgres Pro производится от имени текущего пользователя операционной системы. Все файлы баз данных будут принадлежать этому пользователю.
Чтобы работать с этой базой данных, вы должны будете подключиться к кластеру баз данных под именем пользователя, созданного во время установки. (Это не пользователь операционной системы.)
По умолчанию служба Postgres Pro запускается от имени
NT AUTHORITY\NetworkService
, специального служебного пользователя Windows. При необходимости вы можете выбрать другого пользователя Windows, который будет запускать Postgres Pro, в соответствующем поле инсталлятора. Выбранный вами пользователь должен иметь право запуска служб Windows.
Минимальные системные требования для установки Postgres Pro, создания кластера баз данных и запуска сервера:
Процессор с частотой 1 ГГц
1 ГБ ОЗУ
1 ГБ свободного дискового пространства
Для вспомогательных компонентов или данных потребуется дополнительное дисковое пространство.
17.2.1. Поддерживаемые версии Windows
Postgres Pro выпускается для следующих 64-битных версий Windows:
Windows 10 и новее
Windows Server 2012 R2 и новее
17.2.2. Установка с графическим интерфейсом
Postgres Pro предоставляет инсталлятор с интерактивным мастером, который устанавливает и конфигурирует ключевые компоненты Postgres Pro, создаёт начальную базу данных и настраивает автозапуск сервера. Для следующих компонентов предоставляются индивидуальные инсталляторы, которые должны запускаться отдельно после основного инсталлятора:
pg_probackup
Для установки ключевых компонентов Postgres Pro запустите основной инсталлятор от имени администратора и следуйте инструкциям на экране. Учтите следующую специфику установки:
Вы можете установить все основные компоненты Postgres Pro или настроить инсталляцию, исключив серверную часть или компоненты для разработчика. Клиентская часть устанавливается всегда.
Выбранный каталог данных должен быть пустым. В противном случае Postgres Pro не сможет создать начальную базу данных. По умолчанию каталогом данных будет
C:\Program Files\PostgresProEnterprise\14\data
.Если установлен флажок Allow external connections (Разрешить внешние подключения) (отмеченный по умолчанию), инсталлятор вносит изменения в
postgresql.conf
иpg_hba.conf
для разрешения подключений извне. В противном случае сервер Postgres Pro будет принимать подключения только с локального узла. Если вы решите разрешить внешние подключения после завершения установки, вы должны будете изменить конфигурацию Брандмауэра Windows, чтобы сервер Postgres Pro мог принимать подключения.Запомните имя и пароль пользователя, заданные вами при установке Postgres Pro, так как они потребуются для подключения к серверу Postgres Pro при использовании аутентификации с проверкой пароля.
По умолчанию в Postgres Pro используются правила сортировки
icu
. Если вы обновляете инсталляцию, в которой использовались правила сортировкиlibc
, например, инсталляцию PostgreSQL, выберитеlibc
в качестве провайдера правил сортировки, воспользовавшись соответствующим выпадающим списком в инсталляторе.Postgres Pro предоставляет заранее настроенный ярлык psql, который можно найти в меню Пуск, чтобы вам не пришлось настраивать стандартные переменные окружения. Однако если вы хотели бы работать с Postgres Pro в обычной консоли командной строки, не задавая полные пути к двоичным файлам, отметьте флажок Set up environment variables (Настроить переменные окружения).
По завершении инсталляции экземпляр Postgres Pro готов к использованию, а для службы сервера включён автозапуск. Если вам понадобится больше одного экземпляра Postgres Pro в одной системе, вам нужно будет настроить дополнительные экземпляры вручную. За подробностями обратитесь к Подразделу 17.2.5.
17.2.3. Установка в командной строке
Чтобы установить Postgres Pro из командной строки, запустите загруженный файл инсталлятора, передав один или несколько параметров, описанных в Подразделе 17.2.3.1.
17.2.3.1. Параметры командной строки
Путь каталога инсталляции:
/D=путь
Полностью автоматическая установка:
/S
INI
-файл, содержащий параметры установки сервера:
/init=имя_ini-файла
Если вы хотите скорректировать стандартные параметры, вы должны создать INI
-файл вручную, как описано в Подразделе 17.2.3.2.
17.2.3.2. Формат INI-файла
В разделе [options] данного файла можно задать следующие параметры:
InstallDir
— путь для установки сервера. Если вы зададите параметр /D в командной строке, значениеInstallDir
будет иметь приоритет.DataDir
— путь для создания баз данных по умолчаниюPort
— порт TCP/IP для приёма подключений. По умолчанию: 5432.SuperUser
— имя пользователя, который получит права администратора баз данныхPassword
— пароль этого пользователяnoExtConnections = 1
— не разрешать внешние подключения.Coding = UNICODE
— кодировка символов для использования в базе данныхLocale
— локаль для использования в базе данных (для каждой кодировки может быть несколько локалей)vcredist = no
— не устанавливать распространяемые библиотеки Visual C (это можно сделать, только если эти библиотеки уже установлены в системе)envvar = 1
— установить полезные для Postgres Pro переменные окружения:PGDATA
,PGDATABASE
,PGUSER
,PGPORT
,PGLOCALEDIR
needoptimization = 0
— отключить автоматическую настройку параметров конфигурации в зависимости от имеющихся системных ресурсов.datachecksums = 0
— отключить контрольные суммы в кластере.serviceaccount
— пользователь Windows, от имени которого будет запускаться служба Postgres Pro. Указанный пользователь должен иметь право запуска служб Windows. По умолчанию служба Postgres Pro запускается от имениNT AUTHORITY\NetworkService
, специальной учётной записи для служб Windows.servicepassword
— пароль для пользователя Windows, указанного в параметреserviceaccount
.serviceid
— имя службы Postgres Pro.islibc = 1
— использоватьlibc
в качестве провайдера основного правила сортировки.
17.2.4. Загрузка процедурных языков
В дистрибутив Postgres Pro для систем Windows включены процедурные языки PL/Perl
и PL/Python
.
17.2.4.1. Настройка среды для PL/Python
Чтобы настроить систему для использования PL/Python, выполните следующие действия:
Загрузите и установите последнюю версию Python 3.8 или 2.7 для Windows. Выберите 64-битную версию, так как сервер Postgres Pro имеет 64-битную архитектуру. Вы можете найти подходящий инсталлятор на сайте https://www.python.org/.
Создайте расширение PL/Python, выполнив следующую команду в psql:
CREATE EXTENSION plpythonu
Подсказка
В некоторых случаях при создании функции на PL/Python соединение с сервером разрывается, а в журнал сервера выводится следующее сообщение об ошибке:
ImportError: module site not found
Для устранения этой проблемы попробуйте указать каталог инсталляции Python в переменной окружения PYTHONHOME
и перезапустите службу Postgres Pro.
17.2.4.2. Настройка окружения для PL/Perl
Чтобы настроить систему для использования PL/Perl, выполните следующие действия:
Загрузите Strawberry Perl 5.26, выбрав на странице https://strawberryperl.com/releases.html MSI-пакет 64-битной версии, и установите его.
Перезапустите сервер Postgres Pro.
Создайте расширение PL/Perl, выполнив следующую команду в psql:
CREATE EXTENSION plperlu
17.2.5. Настройка нескольких экземпляров Postgres Pro
Чтобы настроить в Windows несколько экземпляров сервера Postgres Pro с разными каталогами данных, нужно проделать следующее:
Установите Postgres Pro, как описывается в Подразделе 17.2.2 или Подразделе 17.2.3. Установленные двоичные файлы используются всеми экземплярами Postgres Pro, поэтому данное действие нужно выполнить только один раз.
Выберите пустую папку, которую ваш новый экземпляр Postgres Pro будет использовать в качестве каталога данных. Например, это может быть
C:\Program Files\PostgresProEnterprise\14\data2
. К этой папке необходимо дать полный доступ текущему пользователю ОС, который будет владельцем файлов базы, и пользователю, от имени которого работает сервер (по умолчаниюNT AUTHORITY\NetworkService
).Запустите программу initdb, передав ей полный путь к новому каталогу данных и другие параметры, требующиеся для инициализации нового экземпляра сервера. Например:
"C:\Program Files\PostgresProEnterprise\14\bin\initdb.exe" --encoding=UTF8 -U "postgres" -D "C:\Program Files\PostgresProEnterprise\14\data2"
Также вы можете остановить работающий сервер и скопировать содержимое существующего каталога данных в новый каталог. В этом случае новый экземпляр Postgres Pro наследует все свойства исходного экземпляра, включая параметры аутентификации.
Установите в
postgresql.conf
нового экземпляра Postgres Pro требуемые параметры. Обязательно назначьте отдельным экземплярам сервера разные порты во избежание конфликтов.Откройте приглашение командной строки от имени администратора и зарегистрируйте новую службу Postgres Pro с уникальным именем, например,
postgrespro-data2
:"C:\Program Files\PostgresProEnterprise\14\bin\pg_ctl.exe" register -N "postgrespro-data2" -U "NT AUTHORITY\NetworkService" -D "C:\Program Files\PostgresProEnterprise\14\data2" -w
Запустите зарегистрированную службу:
sc start "postgrespro-data2"
После запуска службы ваш экземпляр Postgres Pro готов к использованию. Если вам нужны дополнительные расширения Postgres Pro, установите их в новом экземпляре, как описывается в Разделе 17.3.
17.2.6. Удаление Postgres Pro Enterprise
Процедура удаления Postgres Pro Enterprise зависит от количества экземпляров Postgres Pro, установленных в вашей системе.
Если у вас только один экземпляр Postgres Pro, созданный во время установки, вам будет достаточно запустить программу C:\Program Files\PostgresProEnterprise\14\uninstall.exe
. Эта программа автоматически остановит сервер и разрегистрирует службу, связанную с этим экземпляром.
Если вы создавали дополнительные экземпляры Postgres Pro, вам нужно будет проделать следующие действия:
Остановите сервер для каждого экземпляра:
"C:\Program Files\PostgresProEnterprise\14\bin\pg_ctl.exe" stop -D "C:\Program Files\PostgresProEnterprise\14\
data_dir
" -m fast -wРазрегистрируйте службы для всех экземпляров:
"C:\Program Files\PostgresProEnterprise\14\bin\pg_ctl.exe" unregister -N "
имя_службы_postgrespro
"Запустите
C:\Program Files\PostgresProEnterprise\14\uninstall.exe
, чтобы удалить исполняемые файлы Postgres Pro.
17.2.7. Замечания о совместимости с антивирусами
Настоятельно не рекомендуется использовать антивирусное ПО в системах, где работает Postgres Pro, так как антивирус создаёт дополнительную нагрузку и может оказывать непредсказуемое влияние на работу базы данных, что чревато проблемами с производительностью и надёжностью. Если вам необходимо использовать антивирусное ПО, обязательно добавьте в исключения антивируса следующие каталоги, так как они не содержат исполняемых файлов:
Каталог
PGDATA
с основными данными кластера (обычноC:\Program Files\PostgresProEnterprise\14\data
или другой каталог, заданный в параметрах initdb)Каталоги созданных табличных пространств
17.2. Installing Postgres Pro Enterprise on Windows
Postgres Pro offers the following installation modes for the supported Windows systems:
GUI installation using an interactive wizard
Additionally, you have to set up the environment for using PL/Perl and PL/Python, if these procedural languages are required for your purposes. For details, see Section 17.2.4.
To avoid confusion, note that there are the following different users on Windows systems:
Postgres Pro installation is performed on behalf of an operating system user. All the database files belong to this user.
You must connect to the database cluster on behalf of the user created at installation time to be able to work with the database. This is not an operating system user.
By default, Postgres Pro service is started on behalf of
NT AUTHORITY\NetworkService
, which is a special Windows Service Account. You can specify another Windows user for starting Postgres Pro service in the corresponding text box of the installer, if required. The provided user must have the right to start Windows services.
The minimum hardware required to install Postgres Pro, create a database cluster and start the database server are as follows:
1-GHz
processor1 GB
of RAM1 GB
of disk space
Additional disk space is required for data or supporting components.
17.2.1. Supported Windows Versions
Postgres Pro is available for the following 64-bit Windows versions:
Windows 10 or higher
Windows Server 2012 R2 or higher
17.2.2. GUI Installation
Postgres Pro provides an installer with an interactive wizard that configures and installs Postgres Pro core components, creates the default database, and enables server autostart. The following components have their own installers that should be run separately once the core components are installed:
pg_probackup
To install Postgres Pro core components, run the provided installer as administrator and follow the on-screen instructions. Make sure to take into account the following installation specifics:
You can install all the Postgres Pro core components, or customize the installation by excluding server or developer components. Client utilities are always installed.
The selected data directory must be empty. Otherwise, Postgres Pro cannot create the default database. The default data directory is
C:\Program Files\PostgresProEnterprise\14\data
.If the Allow external connections check box is selected (default), the installer modifies
postgresql.conf
andpg_hba.conf
files to allow external connections. Otherwise, Postgres Pro server is listening for connections from the localhost only. If you decide to enable external connections when the installation is complete, you have to modify the Windows Firewall configuration to allow Postgres Pro server to accept connections.Make sure to remember the username and password you set up when installing Postgres Pro as it will be required to connect to the Postgres Pro server when using password-based authentication methods.
By default, Postgres Pro uses
icu
collations. If you are upgrading an installation with the default collation provided bylibc
, such as PostgreSQL, make sure to chooselibc
collation provider in the corresponding drop-down list of the installer.Postgres Pro provides a pre-configured psql that you can launch from the Start menu, so you do not have to configure the standard environment variables. However, if you would like to work with Postgres Pro from the standard command prompt without specifying full paths to the binary files, select the Set up environment variables check box.
Once the installation completes, your Postgres Pro instance is ready to use, with server autostart enabled. If you need more than one Postgres Pro instance on the same system, you have to configure them manually. For details, see Section 17.2.5.
17.2.3. Command-Line Installation
To install Postgres Pro from the command line, run the downloaded installer file passing one or more options described in Section 17.2.3.1.
17.2.3.1. Command-Line Options
Installation directory path:
/D=path
Silent install:
/S
INI
file that provides the options to customize the server installation:
/init=ini_file_name
If you would like to customize the installation, you must create the INI
file manually, as described in Section 17.2.3.2.
17.2.3.2. INI File Format
You can add the following installation options to the [options] section of the INI file:
InstallDir
— path where to install server. If you specified the /D option on the command line, it will be overwritten by theInstallDir
value.DataDir
— path where to create default databasePort
— TCP/IP port to listen. Default: 5432.SuperUser
— name of the database user who will have admin rights in the databasePassword
— password of the usernoExtConnections = 1
— do not allow external connectionsCoding = UNICODE
— character encoding to use in the databaseLocale
— locale to use in the database. There can be several different locales for each encodingvcredist = no
— do not install Visual C redistributable libraries (use it only if these libraries are already installed on your system)envvar = 1
— set up environment variables helpful for Postgres Pro:PGDATA
,PGDATABASE
,PGUSER
,PGPORT
,PGLOCALEDIR
needoptimization = 0
— disable automatic tuning of configuration parameters based on the available system resources.datachecksums = 0
— disable data checksums for the cluster.serviceaccount
— specify a Windows user for starting Postgres Pro service. The provided user must have the right to start Windows services. By default, Postgres Pro service is started on behalf ofNT AUTHORITY\NetworkService
, which is a special Windows Service Account.servicepassword
— provide the password for the Windows user specified in theserviceaccount
option.serviceid
— change Postgres Pro service name.islibc = 1
— uselibc
as the provider of the default collation.
17.2.4. Loading Procedural Languages
Postgres Pro distribution for Windows systems includes PL/Perl
and PL/Python
procedural languages.
17.2.4.1. Setting up the Environment for PL/Python
To configure the system for using PL/Python, complete the following steps:
Download and install the latest available version of Python 3.8 or 2.7 for Windows. Choose the 64-bit version as Postgres Pro server has 64-bit architecture type. You can find the installers at https://www.python.org/.
Create the PL/Python extension by running the following command in psql:
CREATE EXTENSION plpythonu
Tip
In some cases, when you create a PL/Python function, the connection to the server is lost and the server log shows the following error message:
ImportError: module site not found
To avoid this issue, try to specify the Python installation directory in the PYTHONHOME
environment variable and restart the Postgres Pro service.
17.2.4.2. Setting up the Environment for PL/Perl
To configure the system for using PL/Perl, complete the following steps:
Download the MSI package of the 64-bit Strawberry Perl 5.26 from https://strawberryperl.com/releases.html and perform the installation.
Restart the Postgres Pro server.
Create the PL/Perl extension by running the following command in psql:
CREATE EXTENSION plperlu
17.2.5. Configuring Multiple Postgres Pro Instances
To set up several Postgres Pro server instances with different data directories on Windows, do the following:
Install Postgres Pro as explained in Section 17.2.2 or Section 17.2.3. The installed binary files are shared by all Postgres Pro instances, so you need to complete this step only once.
Select an empty folder that your new Postgres Pro instance will use as the data directory. For example,
C:\Program Files\PostgresProEnterprise\14\data2
. Make sure to grant Full Control permissions for this folder to the current OS user that will own the database files and the user on behalf of which the server is running (NT AUTHORITY\NetworkService
by default).Run initdb specifying the path to the new data directory and any other parameters required to initialize another server instance. For example:
"C:\Program Files\PostgresProEnterprise\14\bin\initdb.exe" --encoding=UTF8 -U "postgres" -D "C:\Program Files\PostgresProEnterprise\14\data2"
Alternatively, you can stop the running server and copy the contents of the existing data directory into the newly created folder. In this case, the new Postgres Pro instance inherits all the settings of the original instance, including authentication settings.
Modify
postgresql.conf
settings for the new Postgres Pro instance as required. Make sure to specify different ports for your server instances to avoid conflicts.Open the command prompt as Administrator and register a new Postgres Pro service with a unique name, for example,
postgrespro-data2
:"C:\Program Files\PostgresProEnterprise\14\bin\pg_ctl.exe" register -N "postgrespro-data2" -U "NT AUTHORITY\NetworkService" -D "C:\Program Files\PostgresProEnterprise\14\data2" -w
Start the registered service:
sc start "postgrespro-data2"
Once the service is started, your Postgres Pro instance is ready to use. If you need any additional Postgres Pro extensions, make sure to enable them for the new instance as explained in Section 17.3.
17.2.6. Uninstalling Postgres Pro Enterprise
The procedure of uninstalling Postgres Pro Enterprise depends on the number of Postgres Pro instances set up on your system.
If you have a single Postgres Pro instance created at installation time, you only need to run the C:\Program Files\PostgresProEnterprise\14\uninstall.exe
program. This program automatically stops the server and unregisters the service for this instance.
If you have created any additional Postgres Pro instances, you have to complete the following steps:
Stop the server for each instance:
"C:\Program Files\PostgresProEnterprise\14\bin\pg_ctl.exe" stop -D "C:\Program Files\PostgresProEnterprise\14\
data_dir
" -m fast -wUnregister the service for each instance:
"C:\Program Files\PostgresProEnterprise\14\bin\pg_ctl.exe" unregister -N "
postgrespro_service_name
"Run the
C:\Program Files\PostgresProEnterprise\14\uninstall.exe
to uninstall Postgres Pro binary files.
17.2.7. Antivirus Considerations
It is strongly recommended to avoid using antivirus software on systems where Postgres Pro is running because it may cause additional load on your environment and result in unexpected database behavior that would lead to performance and reliability issues. If you need to use antivirus software, make sure to exclude the following directories from virus scanning as they do not contain any executable files:
PGDATA
directory that stores main cluster data, usually located inC:\Program Files\PostgresProEnterprise\14\data
unless you specified another directory in initdb optionsPaths to created tablespaces