Как запустить postgresql server windows

I have installed Postgresql on my Windows 10 PC. I have used the pgAdmin II tool to create a database called company, and now I want to start the database server running. I cannot figure out how to do this.
I have run the start command on the postgres command line, and nothing seems to happen.

What I doing is:

postgres=# pg_ctl start
postgres=# pg_ctl status
postgres=# pg_ctl restart
postgres=# pg_ctl start company
postgres=# pg_ctl status

…..-> I am seeing nothing returned.

mikemaccana's user avatar

mikemaccana

112k99 gold badges392 silver badges497 bronze badges

asked Apr 14, 2016 at 17:25

Sean's user avatar

3

Go inside bin folder in C drive where Postgres is installed.
run following command in git bash or Command prompt:

pg_ctl.exe restart -D "<path upto data>"

Ex:

pg_ctl.exe restart -D  "C:\Program Files\PostgreSQL\9.6\data"

Another way:
type «services.msc» in run popup(windows + R).
This will show all services running
Select Postgres service from list and click on start/stop/restart.

Thanks

Tim Biegeleisen's user avatar

answered Oct 5, 2017 at 9:42

Santosh Patel's user avatar

0

If you have installed postgres via the Windows installer you can start it in Services like so:

enter image description here

answered Oct 30, 2018 at 10:28

Matthew Lock's user avatar

Matthew LockMatthew Lock

13.2k12 gold badges92 silver badges130 bronze badges

6

pg_ctl is a command line (Windows) program not a SQL statement. You need to do that from a cmd.exe. Or use net start postgresql-9.5

enter image description here


If you have installed Postgres through the installer, you should start the Windows service instead of running pg_ctl manually, e.g. using:

net start postgresql-9.5

Note that the name of the service might be different in your installation. Another option is to start the service through the Windows control panel


I have used the pgAdmin II tool to create a database called company

Which means that Postgres is already running, so I don’t understand why you think you need to do that again. Especially because the installer typically sets the service to start automatically when Windows is started.


The reason you are not seeing any result is that psql requires every SQL command to be terminated with ; in your case it’s simply waiting for you to finish the statement.

See here for more details: In psql, why do some commands have no effect?

Community's user avatar

answered Apr 14, 2016 at 18:27

4

After a lot of searching and testing, I’ve found a solution.

If you are in Windows

  1. Find the PG Databases directory and execute the following command as a sql command in pgAdmin query tools

    $ show data_directory;

    result :

------------------------
- D:/PG_DATA/data      -
------------------------
  1. Go to the bin directory of your postgres installation (in my case it’s located in «c:/programms/postgresSql/bin»)

  2. Open a command prompt (CMD) and execute the following command:

    pg_ctl -D "D:\PSG_SQL\data" restart

That should do it.

Shawn J. Molloy's user avatar

answered Dec 7, 2016 at 16:41

HichamEch's user avatar

HichamEchHichamEch

6451 gold badge10 silver badges20 bronze badges

2

The simplest way to start/stop/restart the installed PostgreSQL Server on your Windows device is as follows:

  • Start -> net start postgresql-x64-14
  • Stop -> net stop postgresql-x64-14
  • Restart -> net stop postgresql-x64-14 && net start postgresql-x64-14

The version number must be changed to take into account the installed version of your PostgreSQL Server.

answered Dec 1, 2021 at 20:35

RavelRavencroft's user avatar

For windows the following command worked well for me

pg_ctl.exe restart -D «<path_to_data>»

Eg: pg_ctl.exe restart -D «D:\Program Files\PostgreSQL\13\data»

enter image description here

answered Jul 1, 2021 at 17:05

Omprakash Gautam's user avatar

There are different way to open PostgreSql database .
1> One of them is by going windows and select pgAdmin4 or pgAdmin3 depends to version you use and entering password you can access you database .

2> Another one is by terminal :
To able to select from terminal you have to add the path of your installed postgresql by going enviroment variables . To do that got to installed postgresql file and select the path of bin and add to enviroment variable of window setting .
after that you can type in terminal : psql -U postgres -h localhost

Hit enter and it ask you password . After giving password you can create database and tables and can access it .enter image description here

enter image description here

answered Apr 18, 2021 at 15:35

Jeevan Rupacha's user avatar

Jeevan RupachaJeevan Rupacha

3,3351 gold badge16 silver badges29 bronze badges

If you are getting an error «psql.exe’ is not recognized as an internal or external command,… «

There can be :
Causes

  • System is unable to find the psql.exe tool, because the path to this tool is not specified in the system environment variable PATH

or
— PostgreSQL Database client not installed on your PC

Since you have already installed PostgreSQL the latter can not be the issue(assuming everything is installed as expected)

In order to fix the first one «please specify the full path to the bin directory in the PostgreSQL installation folder, where this tool resides.»

For example

Path: «C:\Program Files\PostgreSQL\10\bin»

answered May 10, 2018 at 7:53

Nandan Chaturvedi's user avatar

I found using

net start postgres_service_name

the only reliable way to operate Postgres on Windows

answered May 17, 2018 at 8:23

Tomasz Plonka's user avatar

first find your binaries file where it is saved.
get the path in terminal mine is

C:\Users\LENOVO\Documents\postgresql-9.5.21-1-windows-x64-binaries
(1)\pgsql\bin

then find your local user data path, it is in mostly

C:\usr\local\pgsql\data

now all we have to hit following command in the binary terminal path:

C:\Users\LENOVO\Documents\postgresql-9.5.21-1-windows-x64-binaries (1)\pgsql\bin>pg_ctl -D "C:\usr\local\pgsql\data" start

all done!

autovaccum launcher started! cheers!

answered May 13, 2020 at 23:08

Anupam Maurya's user avatar

Remove Postmaster file in «C:\Program Files\PostgreSQL\9.6\data»

and restart the PostgreSQL services

answered Aug 17, 2019 at 13:10

Kathir M's user avatar

I was try to solve the problem with Windows Terminal and I’ve cannot to solve it. Use Windows R + cmd (if you are using Windows) for it work!

answered Oct 8, 2021 at 18:39

Victor Ruan D Pereira's user avatar

The easiest way to enable pg_ctl command is to go to your PostgreSQL directory ~\PostgreSQL\version\bin\ and execute the pg_ctl.exe. Afterwards the pg_ctl commands will be available.

answered Jan 5, 2021 at 2:11

Ndrslmpk's user avatar

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 11 для windows 10 x64

В процессе установки установите галочки на пунктах:

  • PostgreSQL Server – сам сервер СУБД
  • PgAdmin 4 – визуальный редактор SQL
  • Stack Builder – дополнительные инструменты для разработки (возможно вам они понадобятся в будущем)
  • Command Line Tools – инструменты командной строки

установка PostgreSQL 11 и дополнительных компонентов

Установите пароль для пользователя postgres (он создается по умолчанию и имеет права суперпользователя).

PostgreSQL - задать пароль пользователю postgres

По умолчание СУБД слушает на порту 5432, который нужно будет добавить в исключения в правилах фаерволла.

5432 - порт PostgreSQL по-умолчанию

Нажимаете Далее, Далее, на этом установка 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 отредактируйте файл postgresql.conf по пути C:\Program Files\PostgreSQL\11\data.

Измените значение в пункте
port = 5432
. Перезапустите службу сервера postgresql-x64-11 после изменений. Можно перезапустить службу с помощью PowerShell:

Restart-Service -Name postgresql-x64-11

служба postgresql-x64-11

Более подробно о настройке параметров в конфигурационном файле postgresql.conf с помощью тюнеров смотрите в статье.

Утилиты управления PostgreSQL через командную строку

Рассмотрим управление и основные операции, которые можно выполнять с PostgreSQL через командную строку с помощью нескольких утилит. Основные инструменты управления PostgreSQL находятся в папке bin, потому все команды будем выполнять из данного каталога.

  • Запустите командную строку.

    Совет. Перед запуском СУБД, смените кодировку для нормального отображения в русской Windows 10. В командной строке выполните:
    chcp 1251

  • Перейдите в каталог bin выполнив команду:
    CD C:\Program Files\PostgreSQL\11\bin

утилиты управления postgresql - C:\Program Files\PostgreSQL\11\bin

Основные команды PostgreSQL:

PostgreSQL (shell): psql командная строка

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
);

Query Tool: использование SQL запросов в PostgreSQL

Id — номер сотрудника, которому присвоен ключ SERIAL. Данная строка будет хранить числовое значение 1, 2, 3 и т.д., которое для каждой новой строки будет автоматически увеличиваться на единицу. В следующих строках записаны имя, фамилия сотрудника и его электронный адрес, которые имеют тип CHARACTER VARYING(30), то есть представляют строку длиной не более 30 символов. В строке — Age записан возраст, имеет тип INTEGER, т.к. хранит числа.

После того, как написали код SQL запроса в Query Tool, нажмите клавишу F5 и в базе будет создана новая таблица employee.

Для заполнения полей в свойствах таблицы выберите таблицу employee в разделе Schemas -> Tables. Откройте меню Object инструмент View/Edit Data.

Здесь вы можете заполнить данные в таблице.

редактор таблица в pgadmin

После заполнения данных выполним инструментом Query простой запрос на выборку:
select Age from employee;

выполнить select в PostgreSQL с помощью PgAdmin

  1. Basic PG_CTL Initialization Commands in Windows
  2. Use SERVICES.MSC to START/STOP a PostgreSQL Session in Windows

Start PostgreSQL Server on 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.

  1. Press Windows+R and type in SERVICES.MSC.

  2. 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.

    Windows Services Manager

  3. Right-click on this to either START, STOP, PAUSE, RESUME, or RESTART your server. You can even change the startup time to AUTOMATIC 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.

General tab

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.

General service name

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.

PostgreSQL is an advanced, freely available, and highly stable relational database management system that offers numerous features, such as accuracy, integrity, resilience, etc. The Postgres database is widely used for storing data of web apps, mobile apps, analytical apps, etc. However, to attain any Postgres features, you must know how to start, stop, or restart a Postgres Server.

To tackle such scenarios, Postgres offers different methods, such as the “pg_ctl” utility, “services” manager, etc. This post presents a practical guide on how to start, stop, or restart the PostgreSQL server on the Windows Operating System.

How Do I Start the Postgres Server?

There are various ways to start the Postgres server on Windows, such as using the “net start” command, “pg_ctl” utility, or “services” manager.

Method 1: Starting Postgres Server Using “net start”

Launch the Windows CMD as an administrator and execute the “net start” command to start the Postgres Server:

net start postgresql-x64-15

img

Method 2: Starting Postgres Server Using “pg_ctl”

Firstly, you need to find the directory’s path where Postgres is located. If you didn’t change the default path while installing Postgres, then it must be located in the “Program Files” directory inside the “C” drive.

The complete path will look something like this: “C:\Program Files\PostgreSQL\15\data”:

img

Once you find the complete path, open the CMD and execute the following command to “start the Postgres Server”:

pg_ctl -D "C:\Program Files\PostgreSQL\15\data" start

img

Note: Windows Path for Postgres tools must be set to get the error-free output. Else you will encounter a “not recognized as an internal/external command” error.

Method 3: Starting Postgres Server Using Services Manager

Press the “win” key + “R” to launch the “Run” window. Type the “services.msc” and hit the “OK” button to open the Services Manager:

img

In the “Services Manager”, search for “Postgresql-x64-15”, select the service, and hit the “Start/play” button to start a Postgres server via the “services” manager:

img

Once you press the “start” button the service’s status will be changed to “running”:

img

How to Stop the Postgres Server on Windows?

A Postgres server can be stopped using the “net stop” command, the “pg_ctl” utility, or the “services” manager.

Method 1: Stopping the Postgres Server Using “net stop”

Execute the below-mentioned command from the Command prompt to stop the Postgres Server:

net stop postgresql-x64-15

img

Method 2: Stopping the PostgreSQL Server via the “pg_ctl”

Users may use the “pg_ctl” utility to stop the Postgres server:

pg_ctl -D "C:\Program Files\PostgreSQL\15\data" stop

img

Method 3: Stopping the Postgres Server Using the Services Manager

Open the “Services Manager”, search for “Postgresql-x64-15”, select the service, and hit the “Stop” button to stop a Postgres server via the “services” manager:

img

Clicking on the “Stop” button will stop the Postgres Server.

Note: Similarly, to pause a Postgres Server on Windows, you can select the “pause” button from the Services manager or execute the “net pause postgresql-x64-15” command from the command prompt.

How Do I Restart the Postgres Server on Windows?

You can restart the Postgres server on the windows operating system using the “Services” Manager and “pg_ctl” utility.

Method 1: Restarting the Postgres Server via the “pg_ctl”

Run the below-given command from the CMD to restart the Postgres Server:

pg_ctl -D "C:\Program Files\PostgreSQL\15\data" restart

img

Method 2: Restarting the Postgres Server Using the Services Manager

Launch the “Services Manager”, locate the “Postgresql-x64-15”, select the desired service, and hit the “restart” button to restart a Postgres server via the “services” manager:

img

Clicking on the Restart button will restart the Postgres Server.

Conclusion

There are various ways to start, stop, or restart the Postgres server on Windows, such as using the “net start” command, “pg_ctl” utility, or “services” manager. To get the error-free output, Windows Path for Postgres tools must be set. Else you will encounter a “not recognized as an internal/external command” error. This post presented a practical guide on how to start, stop, or restart the PostgreSQL server on the windows operating system.

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 25.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 be smart, fast, or immediate, 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 the postgres executable is taken from the same directory as pg_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 the postgres executable was not found.

In init mode, this option analogously specifies the location of the initdb 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 the PGCTLTIMEOUT 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, and register, 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), then pg_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 name PostgreSQL.

-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 be auto, or demand, 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.

pg_ctl, like most other PostgreSQL utilities, also uses the environment variables supported by libpq (see Section 34.15).

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 in status 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.

  • Как запустить sacred gold на windows 10
  • Как запустить psql в windows
  • Как запустить roblox на windows 10
  • Как запустить prototype на windows 10
  • Как запустить resident evil village на windows 7