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.
There are several ways to shut down the database server. Under the hood, they all reduce to sending a signal to the supervisor postgres
process.
If you are using a pre-packaged version of PostgreSQL, and you used its provisions for starting the server, then you should also use its provisions for stopping the server. Consult the package-level documentation for details.
When managing the server directly, you can control the type of shutdown by sending different signals to the postgres
process:
- SIGTERM
-
This is the Smart Shutdown mode. After receiving SIGTERM, the server disallows new connections, but lets existing sessions end their work normally. It shuts down only after all of the sessions terminate. If the server is in recovery when a smart shutdown is requested, recovery and streaming replication will be stopped only after all regular sessions have terminated.
- SIGINT
-
This is the Fast Shutdown mode. The server disallows new connections and sends all existing server processes SIGTERM, which will cause them to abort their current transactions and exit promptly. It then waits for all server processes to exit and finally shuts down.
- SIGQUIT
-
This is the Immediate Shutdown mode. The server will send SIGQUIT to all child processes and wait for them to terminate. If any do not terminate within 5 seconds, they will be sent SIGKILL. The supervisor server process exits as soon as all child processes have exited, without doing normal database shutdown processing. This will lead to recovery (by replaying the WAL log) upon next start-up. This is recommended only in emergencies.
The pg_ctl program provides a convenient interface for sending these signals to shut down the server. Alternatively, you can send the signal directly using kill
on non-Windows systems. The PID of the postgres
process can be found using the ps
program, or from the file postmaster.pid
in the data directory. For example, to do a fast shutdown:
$ kill -INT `head -1 /usr/local/pgsql/data/postmaster.pid`
Important
It is best not to use SIGKILL to shut down the server. Doing so will prevent the server from releasing shared memory and semaphores. Furthermore, SIGKILL kills the postgres
process without letting it relay the signal to its subprocesses, so it might be necessary to kill the individual subprocesses by hand as well.
To terminate an individual session while allowing other sessions to continue, use pg_terminate_backend()
(see Table 9.94) or send a SIGTERM signal to the child process associated with the session.
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
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”:
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
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:
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:
Once you press the “start” button the service’s status will be changed to “running”:
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
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
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:
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
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:
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.
In this post, we are going to figure out how to start, stop, and restart a PostgreSQL server on macOS, Linux, and Windows.
1. On macOS
If you installed PostgreSQL via Homebrew:
- To start manually:
pg_ctl -D /usr/local/var/postgres start
- To stop manually:
pg_ctl -D /usr/local/var/postgres stop
- To start PostgreSQL server now and relaunch at login:
brew services start postgresql
- And stop PostgreSQL:
brew services stop postgresql
If you want a hassle-free way to manage the local PostgreSQL database servers, use DBngin. It’s just one click to start, another click to turn off. No dependencies, no command line required, multiple drivers, multiple versions and multiple ports. And it’s free.
2. On Windows
First, you need to find the PostgreSQL database directory, it can be something like C:\Program Files\PostgreSQL\10.4\data
. Then open Command Prompt and execute this command:
pg_ctl -D "C:\Program Files\PostgreSQL\9.6\data" start
- To stop the server
pg_ctl -D "C:\Program Files\PostgreSQL\9.6\data" stop
- To restart the server:
pg_ctl -D "C:\Program Files\PostgreSQL\9.6\data" restart
Another way:
- Open Run Window by
Winkey + R
- Type
services.msc
- Search Postgres service based on version installed.
- Click stop, start or restart the service option.
3. On Linux
Update and install PostgreSQL 10.4
sudo apt-get update
sudo apt-get install postgresql-10.4
By default, the postgres user has no password and can hence only connect if ran by the postgres system user. The following command will assign it:
sudo -u postgres psql -c "ALTER USER postgres PASSWORD 'postgres';"
sudo -u postgres psql -c "CREATE DATABASE testdb;"
- Start the PostgreSQL server
sudo service postgresql start
- Stop the PostgreSQL server:
sudo service postgresql stop
Need a good GUI tool for PostgreSQL on MacOS and Windows? TablePlus is a modern, native tool with an elegant GUI that allows you to simultaneously manage multiple databases such as MySQL, PostgreSQL, SQLite, Microsoft SQL Server and more.
Download TablePlus for Mac. It’s free anyway!
Not on Mac? Download TablePlus for Windows.