Установка PostgreSQL по шагам
1. Загружаем дистрибутив
Мы советуем скачивать актуальные версии на официальном сайте СУБД. Чтобы найти установщик PostgreSQL 15 для Windows нажимаем Download → Windows → Download the installer.
На сайте выбираем интересующую нас версию PostgreSQL и платформу Windows x86-64. Начинается загрузка установочного файла на компьютер.
2. Запускаем установочный файл
В ходе установки проводится проверка на наличие необходимых компонентов, например, Microsoft Visual C++. Если каких-то компонентов не хватает, они устанавливаются автоматически.
В открывшемся приветственном окне нажимаем Next.
3. Указываем каталог для установки
Выбираем путь, куда нужно установить PostgreSQL 15. По умолчанию предлагается C:\Program Files\PostgreSQL\15, его можно оставить.
4. Выбираем дополнительные компоненты
Вместе с СУБД можно установить следующие компоненты:
- PostgreSQL Server — это сам сервер баз данных PostgreSQL;
- pgAdmin 4 — приложение с графическим интерфейсом для администрирования СУБД;
- Stack Builder — утилита, которая поможет установить дополнительные библиотеки и инструменты в PostgreSQL;
- Command Line Tools — инструменты для работы с СУБД через командную строку.
5. Указываем каталог для файлов баз данных
Можно оставить путь по умолчанию C:\Program Files\PostgreSQL\15\data или выбрать свой. Здесь будет храниться вся информация, поэтому перед выбором каталога важно проверить, что на диске достаточно свободного места.
6. Устанавливаем пароль для системного пользователя
Рекомендуем выбирать пароль из 12 и более символов, со строчными и прописными буквами, цифрами и символами. Логин postgres устанавливается по умолчанию.
7. Выбираем порт и кодировку
Можно оставить порт по умолчанию 5432 или указать свой. Далее нажать Next.
В появившемся списке локалей выбираем подходящую для себя локализацию или оставляем значение по умолчанию [Default locale]. Нажимаем Next.
В будущем для новых баз данных на сервере можно будет указать конкретную кодировку.
8. Проверяем параметры и завершаем установку
В финальном окне выводится сводная информация об установке PostgreSQL 15: дополнительные компоненты, выбранные порт и каталог, логин. Если параметры указаны верно, нажимаем Next или возвращаемся для корректировок с помощью кнопки Back.
Все готово. Нажмите Next и дождитесь, когда необходимые компоненты установятся. Обычно процесс занимает не более 5 минут.
Одновременно с завершением процесса установки можно запустить компонент Stack Builder. Если запуск не требуется, снимаем флажок и нажимаем Finish.
Установка приложений с помощью Stack Builder
Запустить Stack Builder после окончания установки PostgreSQL можно с помощью команды:
C:\"Program Files"\PostgreSQL\15\bin\stackbuilder.exe
При этом путь будет зависеть от того, какие диск и каталог были выбраны во время установки СУБД.
В начальном окне Stack Builder выбираем СУБД, для которой будем устанавливать дополнения. Для дальнейшей загрузки необходимо подключение к Интернету.
Далее выбираем дополнительные приложения, которые нужны для работы с базой данных. При клике на любой из компонентов внизу окна появляется его краткое описание. Мы выбрали Migration Toolkit и PEM-HTTPD.
Следующим шагом указываем путь на локальной машине, куда нужно загрузить пакеты выбранных дополнений.
Дожидаемся загрузки файлов.
После этого скачанные приложения устанавливаются по очереди. Перезагружать компьютер следует только после того, как все дополнения из набора будут установлены.
Если устройство все-таки было перезапущено раньше, чем завершилась установка всех приложений, можно запустить инсталляцию с помощью .exe файла. Он находится в папке, которая была выбрана на предыдущем шаге. В нашем примере это папка C:\Program Files\PostgreSQL\additions.
После установки всех выбранных приложений Stack Builder сообщает об успешном завершении.
Запуск pgAdmin 4
pgAdmin 4 — это утилита с простым визуальным интерфейсом, которая помогает работать с PostgreSQL. Ее можно установить отдельно от СУБД, скачав дистрибутив на официальном сайте.
Запустить pgAdmin 4 на устройстве можно через поиск в панели Пуск.
Еще один способ запустить утилиту — ввести в командной строке:
C:\Users\Selectel>C:\"Program Files"\PostgreSQL\15\"pgAdmin 4"\bin\pgAdmin4
Сразу при запуске необходимо придумать мастер пароль. Он нужен для защиты сервера и последующей разблокировки сохраненных паролей.
Чтобы подключиться к серверу СУБД кликните на Servers в левой панели и в раскрывшемся списке выберите PostgreSQL 15. Нажмите на него правой кнопки мыши и выберите Connect Server.
Для подключения нужно ввести пароль пользователя postgres — его мы задавали на этапе установки PostgreSQL 15.
После аутентификации мы подключаемся к своему серверу PostgreSQL 15 и видим все объекты, которые на нем расположены.
Чтобы изменить язык в pgAdmin 4 нажмите в левом верхнем углу File → Preferences. Далее в открывшемся окне в разделе Miscellaneous выберите пункт User language и в выпадающем списке с доступными языками найдите Russian. Язык изменится после перезагрузки страницы.
Сетевой доступ к PostgreSQL
Чтобы сервер PostgreSQL был доступен другим устройствам по сети, необходимо добавить правила в файрволе Windows. Проще всего сделать это с помощью PowerShell или командной строки. При этом команды необходимо выполнять от имени администратора. Еще можно использовать графический интерфейс. Ниже рассмотрим каждый из способов.
PowerShell
New-NetFirewallRule -Name 'POSTGRESQL-PORT' -DisplayName 'Selectel Port PostgreSQL2' -Direction Inbound -Enabled True -Protocol TCP -LocalPort 5432
Командная строка
netsh advfirewall firewall add rule name="Selectel Port PostgreSQL" dir=in action=allow protocol=TCP localport=5432
Графический интерфейс
В меню Пуск ищем брандмауэр и выбираем Брандмауэр Защитника Windows.
В левом меню кликаем на Дополнительные параметры.
Заходим в Правила для входящих подключений и в правой части окна выбираем Создать правило.
Устанавливаем настройки так, как показано на скринах ниже:
На шаге Профиль вы сами решаете, для каких профилей использовать новое правило. Мы оставим все профили включенными.
Задаем имя для нового правила и его описание.
После того, как мы добавили правило в файрволе Windows любым из описанных способов, оно появится в брандмауэре.
Смена порта для подключения к СУБД
Чтобы изменить порт подключения к PostgreSQL находим файл postgresql.conf. Путь к нему — C:\Program Files\PostgreSQL\15\data.
В этом файле ищем строку с указанием port=5432 и меняем номер порта на нужный. Для поиска нужной строки поможет Ctrl+F.
После этого перезапускаем службу postgresql-x64-15 используя встроенное в Windows приложение Службы. Его можно найти в меню Пуск или с помощью команды Win+R на клавиатуре и далее services.msc.
Еще postgresql-x64-15 можно перезапустить с помощью PowerShell. Для этого в консоли PowerShell нужно ввести команду:
Restart-Service-Name postgresql-x64-15
Проверка открытого порта
Проверить открыт ли указанный порт для входящего трафика можно с помощью пробного подключения по протоколу Telnet. Дальше рассмотрим по шагам, как включить этот протокол на Windows 11 и 10.
Telnet на Windows 11
- Через меню Пуск находим и открываем приложение Параметры.
- В открывшемся окне слева выбираем Приложения.
3. В окне Приложения открываем пункт Дополнительные компоненты.
4. В поисковой строке вводим Другие компоненты и открываем указанный параметр.
5. В открывшемся окне находим Клиент Telnet и включаем этот компонент, нажав кнопку ОК.
Telnet на Windows 10
- Через меню Пуск находим и открываем приложение Панель управления.
2. В открывшемся окне находим Программы и компоненты.
3. Кликаем слева на Включение или отключение компонентов Windows.
4. В открывшемся окне находим Клиент Telnet и включаем этот компонент, нажав кнопку ОК.
Теперь протокол Telnet включен и можно проверить открыт ли порт, который прослушивает PostgreSQL. Для этого в командной строке введем:
telnet <IP-address> <Port>
Где IP-address это IP-адрес сервера или его имя, а Port — номер порта, по которому будет производится подключение. Например,
C:\Users\Selectel>telnet 10.0.10.55 5432
Если подключение произошло успешно и порт открыт, будет отображаться пустая командная строка, а имя окна изменится на Telnet <IP-address>.
Если порт закрыт и подключение произвести не удалось, мы увидим сообщение о сбое.
Управление PostgreSQL через командную строку
Чтобы управлять СУБД с помощью командной строки, необходимо открыть ее от имени администратора.
Далее перейти в каталог \bin, так как все основные инструменты PostgreSQL лежат именно в этой папке:
C:\Users\Selectel>cd C:\Program Files\PostgreSQL\15\bin
С помощью параметра -V можно проверить версию СУБД, которая была установлена:
C:\Program Files\PostgreSQL\15\bin>psql -V
Для корректного отображения русских символов в Windows 10 и 11 советуем сменить кодировку на Windows-1251:
C:\Program Files\PostgreSQL\15\bin>chcp 1251
Чтобы создать новую базу данных есть команда:
C:\Program Files\PostgreSQL\15\bin>createdb -U postgres SelectelDatabase
Где:
createdb — сама команда создания новой базы данных;
-U — параметр для указания имени пользователя;
postgres — имя пользователя;
SelecterDatabase — название новой базы данных.
Теперь проверим была ли создана новая база данных. Введем команду с параметром -l, который выводит список доступных баз данных:
C:\Program Files\PostgreSQL\15\bin>psql -U postgres -l
Получаем список:
Чтобы создать нового пользователя воспользуемся командой:
C:\Program Files\PostgreSQL\15\bin>createuser -U postgres TRex
Где:
postgres — пользователь с правами создавать других пользователей;
TRex — имя нового пользователя.
После этого необходимо ввести пароль пользователя postgres, который инициирует команду.
Чтобы сразу изменить пароль для новой роли, можно использовать команду:
postgres=# ALTER ROLE “TRex” WITH PASSWORD 'password';
В команде вместо ‘password’ указать новый пароль.
При вводе SQL запросов важно не забывать ставить ; в конце запроса. Enter без ; в конце строки просто сделает переход на новую строку. Поэтому, если вы забыли ввести ; и нажали Enter, не нужно снова печатать всю строку. Достаточно ввести ; и запрос отправится на сервер.
Чтобы изменить права для новой роли, используется команда ALTER ROLE. Параметр CREATEDB дает право на создание базы данных:
postgres=# ALTER ROLE "TRex" CREATEDB;
Для просмотра ролей и их описания используется команда:
postgres=# \du
Теперь пользователь TRex имеет права на создание базы данных:
Для выхода из postgres можно использовать команду \q или exit.
С помощью командной строки можно также создавать таблицы и заполнять их данными. Для этого сначала подключимся к базе данных SelectelDatabase:
C:\Program Files\PostgreSQL\15\bin>psql -U "postgres" "SelectelDatabase"
Создадим таблицу с цветами Colors, где первое поле idcolor будет автоматически заполняться порядковым номером, а второе поле namecolor содержит наименование цвета:
SelectelDatabase=# CREATE TABLE Colors SelectelDatabase-# (idcolor serial PRIMARY KEY, SelectelDatabase(# namecolor varchar(255) NOT NULL);
Теперь добавим в созданную таблицу данные:
Ввод: SelectelDatabase=# INSERT INTO Colors (namecolor) VALUES ('black'); Вывод: INSERT 0 1 Ввод: SelectelDatabase=# INSERT INTO Colors (namecolor) VALUES ('red'); Вывод: INSERT 0 1 Ввод: SelectelDatabase=# INSERT INTO Colors (namecolor) VALUES ('white'); Вывод: INSERT 0 1 Ввод: SelectelDatabase=# INSERT INTO Colors (namecolor) VALUES ('blue'); Вывод: INSERT 0 1
Выведем на экран содержимое таблицы Colors и увидим, что данные успешно записались:
SelectelDatabase=# SELECT * FROM Colors;
Таблица:
С помощью команды \dt можно посмотреть весь список существующих таблиц в базе данных:
SelectelDatabase=# \dt
Все таблицы:
Команда \d позволяет вывести информацию о конкретной таблице. Так, указав таблицу Colors, мы видим параметры с которыми создана данная таблица:
SelectelDatabase=# \d 'Colors'
Параметры таблицы:
Таблицу можно удалить с помощью функции DROP:
SelectelDatabase=# DROP TABLE Colors;
Query Tool — это редактор SQL запросов в pgAdmin 4 с удобным графическим интерфейсом. На русском редактор называется Запросник.
Открыть запросник можно, нажав на одну из указанных на скриншоте кнопок:
Появляется пустое стартовое окно запросника.
Покажем как работает запросник на примере. Для этого создадим таблицу из пяти полей, где будут указаны рейсы самолетов. Первое поле задается автоматически порядковым номером, второе — точка вылета, третье — точка прилета, четвертое — дата и время отправления, пятое — дата и время прибытия самолета.
Вводим запрос:
CREATE TABLE "flight" ( idflight SERIAL PRIMARY KEY, Apoint VARCHAR(255) NOT NULL, Bpoint VARCHAR(255) NOT NULL, Atime timestamp NOT NULL, Btime timestamp NOT NULL ); INSERT INTO "flight" (Apoint, Bpoint, Atime, Btime) VALUES ('Saint-Petersburg', 'Novosibirsk', '2022-11-24 10:05:00', '2022-11-24 14:15:00'), ('Saint-Petersburg', 'Samara', '2022-11-21 16:45:00', '2022-11-21 18:00:00'), ('Saint-Petersburg', 'Moscow', '2022-11-20 13:20:00', '2022-11-20 14:25:00'), ('Saint-Petersburg', 'Netherlands', '2022-11-23 02:30:00', '2022-11-23 05:15:00'), ('Saint-Petersburg', 'Tashkent', '2022-11-27 06:25:00', '2022-11-27 10:25:00');
Чтобы отобразить введенную информацию выполним команду:
SELECT * FROM "flight";
Получаем вот такую таблицу с рейсами:
С использованием SQL запроса можно отсортировать данные в таблице по определенным условиям. Например укажем, что дата вылета должна быть после полуночи 22 ноября 2022 года и точкой прилета не должен быть Ташкент.
SELECT * FROM "flight" WHERE "atime" > '2022-11-22 00:00:00' AND "bpoint" != 'Tashkent';
Выполнив запрос, получим два рейса, которые подходят под заданные условия:
Заключение
В этой инструкции мы рассмотрели, как установить PostgreSQL на устройство с десктопной версией ОС Windows 10 и 11, а также:
- установили дополнительные приложения с помощью утилиты Stack Builder;
- создали правила файрвола для доступа к PostgreSQL по сети;
- поработали с СУБД через командную строку Windows;
- установили и русифицировали pgAdmin 4;
- рассмотрели работу запросника Query Tool.
PostgreSQL — это бесплатная объектно-реляционная СУБД с мощным функционалом, который позволяет конкурировать с платными базами данных, такими как Microsoft SQL, Oracle. PostgreSQL поддерживает пользовательские данные, функции, операции, домены и индексы. В данной статье мы рассмотрим установку и краткий обзор по управлению базой данных PostgreSQL. Мы установим СУБД PostgreSQL в Windows 10, создадим новую базу, добавим в неё таблицы и настроим доступа для пользователей. Также мы рассмотрим основы управления PostgreSQL с помощью SQL shell и визуальной системы управления PgAdmin. Надеюсь эта статья станет хорошей отправной точкой для обучения работы с PostgreSQL и использованию ее в разработке и тестовых проектах.
Содержание:
- Установка PostgreSQL 11 в Windows 10
- Доступ к PostgreSQL по сети, правила файерволла
- Утилиты управления PostgreSQL через командную строку
- PgAdmin: Визуальный редактор для PostgresSQL
- Query Tool: использование SQL запросов в PostgreSQL
Установка PostgreSQL 11 в Windows 10
Для установки PostgreSQL перейдите на сайт https://www.postgresql.org и скачайте последнюю версию дистрибутива для Windows, на сегодняшний день это версия PostgreSQL 11 (в 11 версии PostgreSQL поддерживаются только 64-х битные редакции Windows). После загрузки запустите инсталлятор.
В процессе установки установите галочки на пунктах:
- PostgreSQL Server – сам сервер СУБД
- PgAdmin 4 – визуальный редактор SQL
- Stack Builder – дополнительные инструменты для разработки (возможно вам они понадобятся в будущем)
- Command Line Tools – инструменты командной строки
Установите пароль для пользователя postgres (он создается по умолчанию и имеет права суперпользователя).
По умолчание СУБД слушает на порту 5432, который нужно будет добавить в исключения в правилах фаерволла.
Нажимаете Далее, Далее, на этом установка PostgreSQL завершена.
Доступ к PostgreSQL по сети, правила файерволла
Чтобы разрешить сетевой доступ к вашему экземпляру PostgreSQL с других компьютеров, вам нужно создать правила в файерволе. Вы можете создать правило через командную строку или PowerShell.
Запустите командную строку от имени администратора. Введите команду:
netsh advfirewall firewall add rule name="Postgre Port" dir=in action=allow protocol=TCP localport=5432
- Где rule name – имя правила
- Localport – разрешенный порт
Либо вы можете создать правило, разрешающее TCP/IP доступ к экземпляру PostgreSQL на порту 5432 с помощью PowerShell:
New-NetFirewallRule -Name 'POSTGRESQL-In-TCP' -DisplayName 'PostgreSQL (TCP-In)' -Direction Inbound -Enabled True -Protocol TCP -LocalPort 5432
После применения команды в брандмауэре Windows появится новое разрешающее правило для порта Postgres.
Совет. Для изменения порта в установленной PostgreSQL отредактируйте файл postgresql.conf по пути C:\Program Files\PostgreSQL\11\data.
Измените значение в пункте
port = 5432
. Перезапустите службу сервера postgresql-x64-11 после изменений. Можно перезапустить службу с помощью PowerShell:
Restart-Service -Name postgresql-x64-11
Более подробно о настройке параметров в конфигурационном файле postgresql.conf с помощью тюнеров смотрите в статье.
Утилиты управления PostgreSQL через командную строку
Рассмотрим управление и основные операции, которые можно выполнять с PostgreSQL через командную строку с помощью нескольких утилит. Основные инструменты управления PostgreSQL находятся в папке bin, потому все команды будем выполнять из данного каталога.
- Запустите командную строку.
Совет. Перед запуском СУБД, смените кодировку для нормального отображения в русской Windows 10. В командной строке выполните:
chcp 1251
- Перейдите в каталог bin выполнив команду:
CD C:\Program Files\PostgreSQL\11\bin
Основные команды PostgreSQL:
PgAdmin: Визуальный редактор для PostgresSQL
Редактор PgAdmin служит для упрощения управления базой данных PostgresSQL в понятном визуальном режиме.
По умолчанию все созданные базы хранятся в каталоге base по пути C:\Program Files\PostgreSQL\11\data\base.
Для каждой БД существует подкаталог внутри PGDATA/base, названный по OID базы данных в pg_database. Этот подкаталог по умолчанию является местом хранения файлов базы данных; в частности, там хранятся её системные каталоги. Каждая таблица и индекс хранятся в отдельном файле.
Для резервного копирования и восстановления лучше использовать инструмент Backup в панели инструментов Tools. Для автоматизации бэкапа PostgreSQL из командной строки используйте утилиту pg_dump.exe.
Query Tool: использование SQL запросов в PostgreSQL
Для написания SQL запросов в удобном графическом редакторе используется встроенный в pgAdmin инструмент Query Tool. Например, вы хотите создать новую таблицу в базе данных через инструмент Query Tool.
- Выберите базу данных, в панели Tools откройте Query Tool
- Создадим таблицу сотрудников:
CREATE TABLE employee
(
Id SERIAL PRIMARY KEY,
FirstName CHARACTER VARYING(30),
LastName CHARACTER VARYING(30),
Email CHARACTER VARYING(30),
Age INTEGER
);
Id — номер сотрудника, которому присвоен ключ SERIAL. Данная строка будет хранить числовое значение 1, 2, 3 и т.д., которое для каждой новой строки будет автоматически увеличиваться на единицу. В следующих строках записаны имя, фамилия сотрудника и его электронный адрес, которые имеют тип CHARACTER VARYING(30), то есть представляют строку длиной не более 30 символов. В строке — Age записан возраст, имеет тип INTEGER, т.к. хранит числа.
После того, как написали код SQL запроса в Query Tool, нажмите клавишу F5 и в базе будет создана новая таблица employee.
Для заполнения полей в свойствах таблицы выберите таблицу employee в разделе Schemas -> Tables. Откройте меню Object инструмент View/Edit Data.
Здесь вы можете заполнить данные в таблице.
После заполнения данных выполним инструментом Query простой запрос на выборку:
select Age from employee;
-
Basic
PG_CTL
Initialization Commands in Windows -
Use
SERVICES.MSC
toSTART/STOP
a PostgreSQL Session in Windows
Today, we will be learning how to start a PostgreSQL server on Windows. In the previous article about downloading and installing PostgreSQL on Windows, we already learned how to start a session, create a USER
, issue queries, and work with different database objects.
Our topic now focuses on trying to run a PostgreSQL server session to which other users in a local system can connect.
Basic PG_CTL
Initialization Commands in Windows
PG_CTL
is a utility used to start and control a PostgreSQL server. PG_CTL
is a manual setup for initializing a PostgreSQL session as it provides a controlled exit, encapsulates different tasks, and can be used for various operations related to our database.
To start a server on Windows, go to your command prompt inside the PostgreSQL installation for the BIN
folder.
pg_ctl start -D "[\data folder directory]";
This will start your PostgreSQL server. To do this on a different port on your computer on which you want other users to listen, use a query as follows.
pg_ctl -o "-F -p [post_number]" start
Enter your PORT NUMBER
in the port_number
defined without the brackets. This will help start your server and allow other users to connect to it on different systems.
However, if your PostgreSQL server stopped due to a reason or a slight malfunction, you are better off using any of the following commands to make it work.
pg_ctl restart -D "[\data folder];
pg_ctl start company; --may or may not work / may produce errors
...
Many times, there will be no need to do any of this. Starting PGADMIN
, for example, tends to already create a PostgreSQL session on a pre-defined port in your PC
, allowing other users to discover it easily.
There may be no need to write any of the commands given above to make your PostgreSQL server boot up.
Specify Paths While Issuing PG_CTL START/RESTART
in Windows
Sometimes, calling a simple PG_CTL START/RESTART
isn’t the way to go. You may need to specify the DATA
folder path within your PostgreSQL installation and then issue the boot commands.
Calling the queries given above, you will get an OUTPUT
.
Output:
pg_ctl: another server might be running; trying to start server anyway
waiting for server to start....2022-04-28 19:28:38.766 PKT [3228] LOG: redirecting log output to logging collector process
2022-04-28 19:28:38.766 PKT [3228] HINT: Future log output will appear in directory "log".
stopped waiting
pg_ctl: could not start server
Examine the log output.
The output given above happens when a PostgreSQL server is already running. Because we already had PGADMIN
booted up and running in the background, calling the query above would be unable to initialize a server on the port already being used.
However, doing something below would run separate servers on the same PC.
pg_ctl -o "-F -p 5656" start -D "C:\Program Files\PostgreSQL\14\data"
Output:
waiting for server to start....2022-04-28 19:34:04.588 PKT [11784] LOG: redirecting log output to logging collector process
2022-04-28 19:34:04.588 PKT [11784] HINT: Future log output will appear in directory "log".
done
server started
Similarly, you could also issue the same commands for RESTART
.
pg_ctl restart -D "C:\Program Files\PostgreSQL\14\data"
or
pg_ctl -o "-F -p 5656" restart -D "C:\Program Files\PostgreSQL\14\data"
Output:
waiting for server to shut down.... done
server stopped
waiting for server to start....2022-04-28 19:35:46.007 PKT [884] LOG: redirecting log output to logging collector process
2022-04-28 19:35:46.007 PKT [884] HINT: Future log output will appear in directory "log".
done
server started
You can see in the output how the server is first shut down because it is already running, then it is restarted and logged for any changes during its session.
Use SERVICES.MSC
to START/STOP
a PostgreSQL Session in Windows
We already know that a PostgreSQL server is instantiated on your PC
when you launch it, either from PSQL
or PGADMIN
. We can do a few things in SERVICES.MSC
For STOPPED
or PAUSED
services, the Windows Services Manager.
-
Press Windows+R and type in
SERVICES.MSC
. -
Once the Windows Services Manager has opened, search for the PostgreSQL server service in the list. It may be named as follows:
postgresql-x64-14 - PostgreSQL Server 14
. -
Right-click on this to either
START
,STOP
,PAUSE
,RESUME
, orRESTART
your server. You can even change the startup time toAUTOMATIC
for it to start by itself the next time.
The Services Manager also tends to tell us the cause of the failure of a specific service. To view the executable path, you can open the General
tab and view it as follows.
Initiate the PostgreSQL Server From the COMMAND PROMPT
Using NET START
We can use the NET START
command to start a service from the command prompt. The syntax is as follows.
You may need to find the SERVICE_NAME
for your PostgreSQL session. It is also mentioned in the General
tab.
Now you can issue a command as follows.
net start postgresql-x64-14;
This will boot up our server and display output as follows.
Output:
The postgresql-x64-14 - PostgreSQL Server 14 service is starting.
The postgresql-x64-14 - PostgreSQL Server 14 service was started successfully.
However, remember that COMMAND PROMPT
needs to be started as an ADMINISTRATOR
and not a normal user.
Right-click on the CMD.EXE
executable file and click Run as Administrator
. Else you will get an error as follows.
Output:
System error 5 has occurred.
Access is denied.
So today, we learned how to start a PostgreSQL server on Windows in different ways. We hope you read through this article carefully and can use it per your needs.
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Step 1: Download and Install PostgreSQL
1. Visit the Official PostgreSQL Website:
Go to the PostgreSQL download page and select the version that matches your Windows environment (32-bit or 64-bit).
2. Run the Installer:
Execute the downloaded installer and follow the on-screen instructions. During installation, you’ll be prompted to set a password for the default PostgreSQL user (postgres). Remember this password as you’ll need it later.
Step 2: Access PostgreSQL Command Line and Graphical Tools
1. Access psql (Command Line Tool):
Open the PostgreSQL command line tool, psql, from the Start Menu or by navigating to the PostgreSQL installation directory. Log in using the postgres user and the password you set during installation.
2. Access pgAdmin (Graphical Tool):
Install and open pgAdmin – a popular graphical administration tool for PostgreSQL. Use it to manage databases, execute SQL queries, and perform other administrative tasks.
Step 3: Create a Database and User
1. Create a Database:
Use the following command in psql or pgAdmin to create a new database:
CREATE DATABASE your_database_name;
2. Create a User:
Create a new user and assign a password:
CREATE USER your_username WITH PASSWORD 'your_password';
Grant the user privileges on the database:
GRANT ALL PRIVILEGES ON DATABASE your_database_name TO your_username;
Step 4: Configure PostgreSQL Server Settings
1. Edit PostgreSQL Configuration File:
Locate the postgresql.conf file in the PostgreSQL data directory (usually found in C:\Program Files\PostgreSQL\version\data). Adjust settings like listen_addresses, port, and other parameters according to your requirements.
Step 5: Enable Remote Access (Optional)
Edit pg_hba.conf:
Open the pg_hba.conf file in the PostgreSQL data directory. Configure it to allow remote connections by adding an entry for your IP address or network range.
Step 6: Start and Stop PostgreSQL Server
1. Start the Server:
Use the Services application to start the PostgreSQL service or run the following command in the command line:
net start postgresql-x64-
2. Stop the Server:
Similarly, use the Services application or the following command to stop the PostgreSQL service:
Step 7: Backup and Restore Databases
1. Backup Database:
Use the pg_dump command to create a backup of your database:
pg_dump -U your_username -d your_database_name -f backup_file.sql
2. Restore Database:
Restore a database using the pg_restore command:
pg_restore -U your_username -d your_database_name -v backup_file.sql
Step 8: Perform Regular Maintenance
1. Vacuuming:
Schedule regular vacuuming tasks to optimize and maintain PostgreSQL performance:
2. Analyze:
Keep statistics up-to-date by running the ANALYZE command:
Step 9: Monitor and Troubleshoot
1. Monitoring Tools:
Utilize monitoring tools like pg_stat_statements and pg_stat_activity to track performance and identify potential issues.
2. Logs:
Check PostgreSQL logs for errors or issues. The log files are typically found in the PostgreSQL data directory.
Conclusion for Setting Up a Windows PostgreSQL Server
By following these steps, you can successfully set up and manage a PostgreSQL server on a Windows environment. Adjustments to these steps may be necessary based on specific use cases and requirements.
pg_ctl — initialize, start, stop, or control a PostgreSQL server
Synopsis
pg_ctl
init[db]
[-D
datadir
] [-s
] [-o
initdb-options
]
pg_ctl
start
[-D
datadir
] [-l
filename
] [-W
] [-t
seconds
] [-s
] [-o
options
] [-p
path
] [-c
]
pg_ctl
stop
[-D
datadir
] [-m
s[mart]
| f[ast]
| i[mmediate]
] [-W
] [-t
seconds
] [-s
]
pg_ctl
restart
[-D
datadir
] [-m
s[mart]
| f[ast]
| i[mmediate]
] [-W
] [-t
seconds
] [-s
] [-o
options
] [-c
]
pg_ctl
reload
[-D
datadir
] [-s
]
pg_ctl
status
[-D
datadir
]
pg_ctl
promote
[-D
datadir
] [-W
] [-t
seconds
] [-s
]
pg_ctl
logrotate
[-D
datadir
] [-s
]
pg_ctl
kill
signal_name
process_id
On Microsoft Windows, also:
pg_ctl
register
[-D
datadir
] [-N
servicename
] [-U
username
] [-P
password
] [-S
a[uto]
| d[emand]
] [-e
source
] [-W
] [-t
seconds
] [-s
] [-o
options
]
pg_ctl
unregister
[-N
servicename
]
Description
pg_ctl is a utility for initializing a PostgreSQL database cluster, starting, stopping, or restarting the PostgreSQL database server (postgres), or displaying the status of a running server. Although the server can be started manually, pg_ctl encapsulates tasks such as redirecting log output and properly detaching from the terminal and process group. It also provides convenient options for controlled shutdown.
The init
or initdb
mode creates a new PostgreSQL database cluster, that is, a collection of databases that will be managed by a single server instance. This mode invokes the initdb
command. See initdb for details.
start
mode launches a new server. The server is started in the background, and its standard input is attached to /dev/null
(or nul
on Windows). On Unix-like systems, by default, the server’s standard output and standard error are sent to pg_ctl‘s standard output (not standard error). The standard output of pg_ctl should then be redirected to a file or piped to another process such as a log rotating program like rotatelogs; otherwise postgres
will write its output to the controlling terminal (from the background) and will not leave the shell’s process group. On Windows, by default the server’s standard output and standard error are sent to the terminal. These default behaviors can be changed by using -l
to append the server’s output to a log file. Use of either -l
or output redirection is recommended.
stop
mode shuts down the server that is running in the specified data directory. Three different shutdown methods can be selected with the -m
option. “Smart” mode disallows new connections, then waits for all existing clients to disconnect. If the server is in hot standby, recovery and streaming replication will be terminated once all clients have disconnected. “Fast” mode (the default) does not wait for clients to disconnect. All active transactions are rolled back and clients are forcibly disconnected, then the server is shut down. “Immediate” mode will abort all server processes immediately, without a clean shutdown. This choice will lead to a crash-recovery cycle during the next server start.
restart
mode effectively executes a stop followed by a start. This allows changing the postgres
command-line options, or changing configuration-file options that cannot be changed without restarting the server. If relative paths were used on the command line during server start, restart
might fail unless pg_ctl is executed in the same current directory as it was during server start.
reload
mode simply sends the postgres
server process a SIGHUP signal, causing it to reread its configuration files (postgresql.conf
, pg_hba.conf
, etc.). This allows changing configuration-file options that do not require a full server restart to take effect.
status
mode checks whether a server is running in the specified data directory. If it is, the server’s PID and the command line options that were used to invoke it are displayed. If the server is not running, pg_ctl returns an exit status of 3. If an accessible data directory is not specified, pg_ctl returns an exit status of 4.
promote
mode commands the standby server that is running in the specified data directory to end standby mode and begin read-write operations.
logrotate
mode rotates the server log file. For details on how to use this mode with external log rotation tools, see Section 24.3.
kill
mode sends a signal to a specified process. This is primarily valuable on Microsoft Windows which does not have a built-in kill command. Use --help
to see a list of supported signal names.
register
mode registers the PostgreSQL server as a system service on Microsoft Windows. The -S
option allows selection of service start type, either “auto” (start service automatically on system startup) or “demand” (start service on demand).
unregister
mode unregisters a system service on Microsoft Windows. This undoes the effects of the register
command.
Options
-c
--core-files
-
Attempt to allow server crashes to produce core files, on platforms where this is possible, by lifting any soft resource limit placed on core files. This is useful in debugging or diagnosing problems by allowing a stack trace to be obtained from a failed server process.
-D
datadir
--pgdata=
datadir
-
Specifies the file system location of the database configuration files. If this option is omitted, the environment variable
PGDATA
is used. -l
filename
--log=
filename
-
Append the server log output to
filename
. If the file does not exist, it is created. The umask is set to 077, so access to the log file is disallowed to other users by default. -m
mode
--mode=
mode
-
Specifies the shutdown mode.
mode
can besmart
,fast
, orimmediate
, or the first letter of one of these three. If this option is omitted,fast
is the default. -o
options
--options=
options
-
Specifies options to be passed directly to the
postgres
command.-o
can be specified multiple times, with all the given options being passed through.The
options
should usually be surrounded by single or double quotes to ensure that they are passed through as a group. -o
initdb-options
--options=
initdb-options
-
Specifies options to be passed directly to the
initdb
command.-o
can be specified multiple times, with all the given options being passed through.The
initdb-options
should usually be surrounded by single or double quotes to ensure that they are passed through as a group. -p
path
-
Specifies the location of the
postgres
executable. By default thepostgres
executable is taken from the same directory aspg_ctl
, or failing that, the hard-wired installation directory. It is not necessary to use this option unless you are doing something unusual and get errors that thepostgres
executable was not found.In
init
mode, this option analogously specifies the location of theinitdb
executable. -s
--silent
-
Print only errors, no informational messages.
-t
seconds
--timeout=
seconds
-
Specifies the maximum number of seconds to wait when waiting for an operation to complete (see option
-w
). Defaults to the value of thePGCTLTIMEOUT
environment variable or, if not set, to 60 seconds. -V
--version
-
Print the pg_ctl version and exit.
-w
--wait
-
Wait for the operation to complete. This is supported for the modes
start
,stop
,restart
,promote
, andregister
, and is the default for those modes.When waiting,
pg_ctl
repeatedly checks the server’s PID file, sleeping for a short amount of time between checks. Startup is considered complete when the PID file indicates that the server is ready to accept connections. Shutdown is considered complete when the server removes the PID file.pg_ctl
returns an exit code based on the success of the startup or shutdown.If the operation does not complete within the timeout (see option
-t
), thenpg_ctl
exits with a nonzero exit status. But note that the operation might continue in the background and eventually succeed. -W
--no-wait
-
Do not wait for the operation to complete. This is the opposite of the option
-w
.If waiting is disabled, the requested action is triggered, but there is no feedback about its success. In that case, the server log file or an external monitoring system would have to be used to check the progress and success of the operation.
In prior releases of PostgreSQL, this was the default except for the
stop
mode. -?
--help
-
Show help about pg_ctl command line arguments, and exit.
If an option is specified that is valid, but not relevant to the selected operating mode, pg_ctl ignores it.
Options for Windows
-e
source
-
Name of the event source for pg_ctl to use for logging to the event log when running as a Windows service. The default is
PostgreSQL
. Note that this only controls messages sent from pg_ctl itself; once started, the server will use the event source specified by its event_source parameter. Should the server fail very early in startup, before that parameter has been set, it might also log using the default event source namePostgreSQL
. -N
servicename
-
Name of the system service to register. This name will be used as both the service name and the display name. The default is
PostgreSQL
. -P
password
-
Password for the user to run the service as.
-S
start-type
-
Start type of the system service.
start-type
can beauto
, ordemand
, or the first letter of one of these two. If this option is omitted,auto
is the default. -U
username
-
User name for the user to run the service as. For domain users, use the format
DOMAIN\username
.
Environment
PGCTLTIMEOUT
-
Default limit on the number of seconds to wait when waiting for startup or shutdown to complete. If not set, the default is 60 seconds.
PGDATA
-
Default data directory location.
Most pg_ctl
modes require knowing the data directory location; therefore, the -D
option is required unless PGDATA
is set.
For additional variables that affect the server, see postgres.
Files
postmaster.pid
-
pg_ctl examines this file in the data directory to determine whether the server is currently running.
postmaster.opts
-
If this file exists in the data directory, pg_ctl (in
restart
mode) will pass the contents of the file as options to postgres, unless overridden by the-o
option. The contents of this file are also displayed instatus
mode.
Examples
Starting the Server
To start the server, waiting until the server is accepting connections:
$
pg_ctl start
To start the server using port 5433, and running without fsync
, use:
$
pg_ctl -o "-F -p 5433" start
Stopping the Server
To stop the server, use:
$
pg_ctl stop
The -m
option allows control over how the server shuts down:
$
pg_ctl stop -m smart
Restarting the Server
Restarting the server is almost equivalent to stopping the server and starting it again, except that by default, pg_ctl
saves and reuses the command line options that were passed to the previously-running instance. To restart the server using the same options as before, use:
$
pg_ctl restart
But if -o
is specified, that replaces any previous options. To restart using port 5433, disabling fsync
upon restart:
$
pg_ctl -o "-F -p 5433" restart
Showing the Server Status
Here is sample status output from pg_ctl:
$
pg_ctl status
pg_ctl: server is running (PID: 13718) /usr/local/pgsql/bin/postgres "-D" "/usr/local/pgsql/data" "-p" "5433" "-B" "128"
The second line is the command that would be invoked in restart mode.