Before anyone can access the database, you must start the database server. The database server program is called postgres
.
If you are using a pre-packaged version of PostgreSQL, it almost certainly includes provisions for running the server as a background task according to the conventions of your operating system. Using the package’s infrastructure to start the server will be much less work than figuring out how to do this yourself. Consult the package-level documentation for details.
The bare-bones way to start the server manually is just to invoke postgres
directly, specifying the location of the data directory with the -D
option, for example:
$ postgres -D /usr/local/pgsql/data
which will leave the server running in the foreground. This must be done while logged into the PostgreSQL user account. Without -D
, the server will try to use the data directory named by the environment variable PGDATA
. If that variable is not provided either, it will fail.
Normally it is better to start postgres
in the background. For this, use the usual Unix shell syntax:
$ postgres -D /usr/local/pgsql/data >logfile 2>&1 &
It is important to store the server’s stdout and stderr output somewhere, as shown above. It will help for auditing purposes and to diagnose problems. (See Section 25.3 for a more thorough discussion of log file handling.)
The postgres
program also takes a number of other command-line options. For more information, see the postgres reference page and Chapter 20 below.
This shell syntax can get tedious quickly. Therefore the wrapper program pg_ctl is provided to simplify some tasks. For example:
pg_ctl start -l logfile
will start the server in the background and put the output into the named log file. The -D
option has the same meaning here as for postgres
. pg_ctl
is also capable of stopping the server.
Normally, you will want to start the database server when the computer boots. Autostart scripts are operating-system-specific. There are a few example scripts distributed with PostgreSQL in the contrib/start-scripts
directory. Installing one will require root privileges.
Different systems have different conventions for starting up daemons at boot time. Many systems have a file /etc/rc.local
or /etc/rc.d/rc.local
. Others use init.d
or rc.d
directories. Whatever you do, the server must be run by the PostgreSQL user account and not by root or any other user. Therefore you probably should form your commands using su postgres -c '...'
. For example:
su postgres -c 'pg_ctl start -D /usr/local/pgsql/data -l serverlog'
Here are a few more operating-system-specific suggestions. (In each case be sure to use the proper installation directory and user name where we show generic values.)
-
For FreeBSD, look at the file
contrib/start-scripts/freebsd
in the PostgreSQL source distribution. -
On OpenBSD, add the following lines to the file
/etc/rc.local
:if [ -x /usr/local/pgsql/bin/pg_ctl -a -x /usr/local/pgsql/bin/postgres ]; then su -l postgres -c '/usr/local/pgsql/bin/pg_ctl start -s -l /var/postgresql/log -D /usr/local/pgsql/data' echo -n ' postgresql' fi
-
On Linux systems either add
/usr/local/pgsql/bin/pg_ctl start -l logfile -D /usr/local/pgsql/data
to
/etc/rc.d/rc.local
or/etc/rc.local
or look at the filecontrib/start-scripts/linux
in the PostgreSQL source distribution.When using systemd, you can use the following service unit file (e.g., at
/etc/systemd/system/postgresql.service
):[Unit] Description=PostgreSQL database server Documentation=man:postgres(1) After=network-online.target Wants=network-online.target [Service] Type=notify User=postgres ExecStart=/usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data ExecReload=/bin/kill -HUP $MAINPID KillMode=mixed KillSignal=SIGINT TimeoutSec=infinity [Install] WantedBy=multi-user.target
Using
Type=notify
requires that the server binary was built withconfigure --with-systemd
.Consider carefully the timeout setting. systemd has a default timeout of 90 seconds as of this writing and will kill a process that does not report readiness within that time. But a PostgreSQL server that might have to perform crash recovery at startup could take much longer to become ready. The suggested value of
infinity
disables the timeout logic. -
On NetBSD, use either the FreeBSD or Linux start scripts, depending on preference.
-
On Solaris, create a file called
/etc/init.d/postgresql
that contains the following line:su - postgres -c "/usr/local/pgsql/bin/pg_ctl start -l logfile -D /usr/local/pgsql/data"
Then, create a symbolic link to it in
/etc/rc3.d
asS99postgresql
.
While the server is running, its PID is stored in the file postmaster.pid
in the data directory. This is used to prevent multiple server instances from running in the same data directory and can also be used for shutting down the server.
19.3.1. Server Start-up Failures
There are several common reasons the server might fail to start. Check the server’s log file, or start it by hand (without redirecting standard output or standard error) and see what error messages appear. Below we explain some of the most common error messages in more detail.
LOG: could not bind IPv4 address "127.0.0.1": Address already in use HINT: Is another postmaster already running on port 5432? If not, wait a few seconds and retry. FATAL: could not create any TCP/IP sockets
This usually means just what it suggests: you tried to start another server on the same port where one is already running. However, if the kernel error message is not Address already in use
or some variant of that, there might be a different problem. For example, trying to start a server on a reserved port number might draw something like:
$ postgres -p 666
LOG: could not bind IPv4 address "127.0.0.1": Permission denied
HINT: Is another postmaster already running on port 666? If not, wait a few seconds and retry.
FATAL: could not create any TCP/IP sockets
A message like:
FATAL: could not create shared memory segment: Invalid argument DETAIL: Failed system call was shmget(key=5440001, size=4011376640, 03600).
probably means your kernel’s limit on the size of shared memory is smaller than the work area PostgreSQL is trying to create (4011376640 bytes in this example). This is only likely to happen if you have set shared_memory_type
to sysv
. In that case, you can try starting the server with a smaller-than-normal number of buffers (shared_buffers), or reconfigure your kernel to increase the allowed shared memory size. You might also see this message when trying to start multiple servers on the same machine, if their total space requested exceeds the kernel limit.
An error like:
FATAL: could not create semaphores: No space left on device DETAIL: Failed system call was semget(5440126, 17, 03600).
does not mean you’ve run out of disk space. It means your kernel’s limit on the number of System V semaphores is smaller than the number PostgreSQL wants to create. As above, you might be able to work around the problem by starting the server with a reduced number of allowed connections (max_connections), but you’ll eventually want to increase the kernel limit.
Details about configuring System V IPC facilities are given in Section 19.4.1.
19.3.2. Client Connection Problems
Although the error conditions possible on the client side are quite varied and application-dependent, a few of them might be directly related to how the server was started. Conditions other than those shown below should be documented with the respective client application.
psql: error: connection to server at "server.joe.com" (123.123.123.123), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections?
This is the generic “I couldn’t find a server to talk to” failure. It looks like the above when TCP/IP communication is attempted. A common mistake is to forget to configure the server to allow TCP/IP connections.
Alternatively, you might get this when attempting Unix-domain socket communication to a local server:
psql: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket?
If the server is indeed running, check that the client’s idea of the socket path (here /tmp
) agrees with the server’s unix_socket_directories setting.
A connection failure message always shows the server address or socket path name, which is useful in verifying that the client is trying to connect to the right place. If there is in fact no server listening there, the kernel error message will typically be either Connection refused
or No such file or directory
, as illustrated. (It is important to realize that Connection refused
in this context does not mean that the server got your connection request and rejected it. That case will produce a different message, as shown in Section 21.15.) Other error messages such as Connection timed out
might indicate more fundamental problems, like lack of network connectivity, or a firewall blocking the connection.
Before anyone can access the database, you must start the database server. The database server program is called postgres
.
If you are using a pre-packaged version of PostgreSQL, it almost certainly includes provisions for running the server as a background task according to the conventions of your operating system. Using the package’s infrastructure to start the server will be much less work than figuring out how to do this yourself. Consult the package-level documentation for details.
The bare-bones way to start the server manually is just to invoke postgres
directly, specifying the location of the data directory with the -D
option, for example:
$ postgres -D /usr/local/pgsql/data
which will leave the server running in the foreground. This must be done while logged into the PostgreSQL user account. Without -D
, the server will try to use the data directory named by the environment variable PGDATA
. If that variable is not provided either, it will fail.
Normally it is better to start postgres
in the background. For this, use the usual Unix shell syntax:
$ postgres -D /usr/local/pgsql/data >logfile 2>&1 &
It is important to store the server’s stdout and stderr output somewhere, as shown above. It will help for auditing purposes and to diagnose problems. (See Section 25.3 for a more thorough discussion of log file handling.)
The postgres
program also takes a number of other command-line options. For more information, see the postgres reference page and Chapter 20 below.
This shell syntax can get tedious quickly. Therefore the wrapper program pg_ctl is provided to simplify some tasks. For example:
pg_ctl start -l logfile
will start the server in the background and put the output into the named log file. The -D
option has the same meaning here as for postgres
. pg_ctl
is also capable of stopping the server.
Normally, you will want to start the database server when the computer boots. Autostart scripts are operating-system-specific. There are a few example scripts distributed with PostgreSQL in the contrib/start-scripts
directory. Installing one will require root privileges.
Different systems have different conventions for starting up daemons at boot time. Many systems have a file /etc/rc.local
or /etc/rc.d/rc.local
. Others use init.d
or rc.d
directories. Whatever you do, the server must be run by the PostgreSQL user account and not by root or any other user. Therefore you probably should form your commands using su postgres -c '...'
. For example:
su postgres -c 'pg_ctl start -D /usr/local/pgsql/data -l serverlog'
Here are a few more operating-system-specific suggestions. (In each case be sure to use the proper installation directory and user name where we show generic values.)
-
For FreeBSD, look at the file
contrib/start-scripts/freebsd
in the PostgreSQL source distribution. -
On OpenBSD, add the following lines to the file
/etc/rc.local
:if [ -x /usr/local/pgsql/bin/pg_ctl -a -x /usr/local/pgsql/bin/postgres ]; then su -l postgres -c '/usr/local/pgsql/bin/pg_ctl start -s -l /var/postgresql/log -D /usr/local/pgsql/data' echo -n ' postgresql' fi
-
On Linux systems either add
/usr/local/pgsql/bin/pg_ctl start -l logfile -D /usr/local/pgsql/data
to
/etc/rc.d/rc.local
or/etc/rc.local
or look at the filecontrib/start-scripts/linux
in the PostgreSQL source distribution.When using systemd, you can use the following service unit file (e.g., at
/etc/systemd/system/postgresql.service
):[Unit] Description=PostgreSQL database server Documentation=man:postgres(1) After=network-online.target Wants=network-online.target [Service] Type=notify User=postgres ExecStart=/usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data ExecReload=/bin/kill -HUP $MAINPID KillMode=mixed KillSignal=SIGINT TimeoutSec=infinity [Install] WantedBy=multi-user.target
Using
Type=notify
requires that the server binary was built withconfigure --with-systemd
.Consider carefully the timeout setting. systemd has a default timeout of 90 seconds as of this writing and will kill a process that does not report readiness within that time. But a PostgreSQL server that might have to perform crash recovery at startup could take much longer to become ready. The suggested value of
infinity
disables the timeout logic. -
On NetBSD, use either the FreeBSD or Linux start scripts, depending on preference.
-
On Solaris, create a file called
/etc/init.d/postgresql
that contains the following line:su - postgres -c "/usr/local/pgsql/bin/pg_ctl start -l logfile -D /usr/local/pgsql/data"
Then, create a symbolic link to it in
/etc/rc3.d
asS99postgresql
.
While the server is running, its PID is stored in the file postmaster.pid
in the data directory. This is used to prevent multiple server instances from running in the same data directory and can also be used for shutting down the server.
19.3.1. Server Start-up Failures
There are several common reasons the server might fail to start. Check the server’s log file, or start it by hand (without redirecting standard output or standard error) and see what error messages appear. Below we explain some of the most common error messages in more detail.
LOG: could not bind IPv4 address "127.0.0.1": Address already in use HINT: Is another postmaster already running on port 5432? If not, wait a few seconds and retry. FATAL: could not create any TCP/IP sockets
This usually means just what it suggests: you tried to start another server on the same port where one is already running. However, if the kernel error message is not Address already in use
or some variant of that, there might be a different problem. For example, trying to start a server on a reserved port number might draw something like:
$ postgres -p 666
LOG: could not bind IPv4 address "127.0.0.1": Permission denied
HINT: Is another postmaster already running on port 666? If not, wait a few seconds and retry.
FATAL: could not create any TCP/IP sockets
A message like:
FATAL: could not create shared memory segment: Invalid argument DETAIL: Failed system call was shmget(key=5440001, size=4011376640, 03600).
probably means your kernel’s limit on the size of shared memory is smaller than the work area PostgreSQL is trying to create (4011376640 bytes in this example). This is only likely to happen if you have set shared_memory_type
to sysv
. In that case, you can try starting the server with a smaller-than-normal number of buffers (shared_buffers), or reconfigure your kernel to increase the allowed shared memory size. You might also see this message when trying to start multiple servers on the same machine, if their total space requested exceeds the kernel limit.
An error like:
FATAL: could not create semaphores: No space left on device DETAIL: Failed system call was semget(5440126, 17, 03600).
does not mean you’ve run out of disk space. It means your kernel’s limit on the number of System V semaphores is smaller than the number PostgreSQL wants to create. As above, you might be able to work around the problem by starting the server with a reduced number of allowed connections (max_connections), but you’ll eventually want to increase the kernel limit.
Details about configuring System V IPC facilities are given in Section 19.4.1.
19.3.2. Client Connection Problems
Although the error conditions possible on the client side are quite varied and application-dependent, a few of them might be directly related to how the server was started. Conditions other than those shown below should be documented with the respective client application.
psql: error: connection to server at "server.joe.com" (123.123.123.123), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections?
This is the generic “I couldn’t find a server to talk to” failure. It looks like the above when TCP/IP communication is attempted. A common mistake is to forget to configure the server to allow TCP/IP connections.
Alternatively, you might get this when attempting Unix-domain socket communication to a local server:
psql: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket?
If the server is indeed running, check that the client’s idea of the socket path (here /tmp
) agrees with the server’s unix_socket_directories setting.
A connection failure message always shows the server address or socket path name, which is useful in verifying that the client is trying to connect to the right place. If there is in fact no server listening there, the kernel error message will typically be either Connection refused
or No such file or directory
, as illustrated. (It is important to realize that Connection refused
in this context does not mean that the server got your connection request and rejected it. That case will produce a different message, as shown in Section 21.15.) Other error messages such as Connection timed out
might indicate more fundamental problems, like lack of network connectivity, or a firewall blocking the connection.
Before anyone can access the database, you must start the database server. The database server program is called postgres
.
If you are using a pre-packaged version of PostgreSQL, it almost certainly includes provisions for running the server as a background task according to the conventions of your operating system. Using the package’s infrastructure to start the server will be much less work than figuring out how to do this yourself. Consult the package-level documentation for details.
The bare-bones way to start the server manually is just to invoke postgres
directly, specifying the location of the data directory with the -D
option, for example:
$ postgres -D /usr/local/pgsql/data
which will leave the server running in the foreground. This must be done while logged into the PostgreSQL user account. Without -D
, the server will try to use the data directory named by the environment variable PGDATA
. If that variable is not provided either, it will fail.
Normally it is better to start postgres
in the background. For this, use the usual Unix shell syntax:
$ postgres -D /usr/local/pgsql/data >logfile 2>&1 &
It is important to store the server’s stdout and stderr output somewhere, as shown above. It will help for auditing purposes and to diagnose problems. (See Section 24.3 for a more thorough discussion of log file handling.)
The postgres
program also takes a number of other command-line options. For more information, see the postgres reference page and Chapter 19 below.
This shell syntax can get tedious quickly. Therefore the wrapper program pg_ctl is provided to simplify some tasks. For example:
pg_ctl start -l logfile
will start the server in the background and put the output into the named log file. The -D
option has the same meaning here as for postgres
. pg_ctl
is also capable of stopping the server.
Normally, you will want to start the database server when the computer boots. Autostart scripts are operating-system-specific. There are a few example scripts distributed with PostgreSQL in the contrib/start-scripts
directory. Installing one will require root privileges.
Different systems have different conventions for starting up daemons at boot time. Many systems have a file /etc/rc.local
or /etc/rc.d/rc.local
. Others use init.d
or rc.d
directories. Whatever you do, the server must be run by the PostgreSQL user account and not by root or any other user. Therefore you probably should form your commands using su postgres -c '...'
. For example:
su postgres -c 'pg_ctl start -D /usr/local/pgsql/data -l serverlog'
Here are a few more operating-system-specific suggestions. (In each case be sure to use the proper installation directory and user name where we show generic values.)
-
For FreeBSD, look at the file
contrib/start-scripts/freebsd
in the PostgreSQL source distribution. -
On OpenBSD, add the following lines to the file
/etc/rc.local
:if [ -x /usr/local/pgsql/bin/pg_ctl -a -x /usr/local/pgsql/bin/postgres ]; then su -l postgres -c '/usr/local/pgsql/bin/pg_ctl start -s -l /var/postgresql/log -D /usr/local/pgsql/data' echo -n ' postgresql' fi
-
On Linux systems either add
/usr/local/pgsql/bin/pg_ctl start -l logfile -D /usr/local/pgsql/data
to
/etc/rc.d/rc.local
or/etc/rc.local
or look at the filecontrib/start-scripts/linux
in the PostgreSQL source distribution.When using systemd, you can use the following service unit file (e.g., at
/etc/systemd/system/postgresql.service
):[Unit] Description=PostgreSQL database server Documentation=man:postgres(1) After=network-online.target Wants=network-online.target [Service] Type=notify User=postgres ExecStart=/usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data ExecReload=/bin/kill -HUP $MAINPID KillMode=mixed KillSignal=SIGINT TimeoutSec=infinity [Install] WantedBy=multi-user.target
Using
Type=notify
requires that the server binary was built withconfigure --with-systemd
.Consider carefully the timeout setting. systemd has a default timeout of 90 seconds as of this writing and will kill a process that does not report readiness within that time. But a PostgreSQL server that might have to perform crash recovery at startup could take much longer to become ready. The suggested value of
infinity
disables the timeout logic. -
On NetBSD, use either the FreeBSD or Linux start scripts, depending on preference.
-
On Solaris, create a file called
/etc/init.d/postgresql
that contains the following line:su - postgres -c "/usr/local/pgsql/bin/pg_ctl start -l logfile -D /usr/local/pgsql/data"
Then, create a symbolic link to it in
/etc/rc3.d
asS99postgresql
.
While the server is running, its PID is stored in the file postmaster.pid
in the data directory. This is used to prevent multiple server instances from running in the same data directory and can also be used for shutting down the server.
18.3.1. Server Start-up Failures
There are several common reasons the server might fail to start. Check the server’s log file, or start it by hand (without redirecting standard output or standard error) and see what error messages appear. Below we explain some of the most common error messages in more detail.
LOG: could not bind IPv4 address "127.0.0.1": Address already in use HINT: Is another postmaster already running on port 5432? If not, wait a few seconds and retry. FATAL: could not create any TCP/IP sockets
This usually means just what it suggests: you tried to start another server on the same port where one is already running. However, if the kernel error message is not Address already in use
or some variant of that, there might be a different problem. For example, trying to start a server on a reserved port number might draw something like:
$ postgres -p 666
LOG: could not bind IPv4 address "127.0.0.1": Permission denied
HINT: Is another postmaster already running on port 666? If not, wait a few seconds and retry.
FATAL: could not create any TCP/IP sockets
A message like:
FATAL: could not create shared memory segment: Invalid argument DETAIL: Failed system call was shmget(key=5440001, size=4011376640, 03600).
probably means your kernel’s limit on the size of shared memory is smaller than the work area PostgreSQL is trying to create (4011376640 bytes in this example). This is only likely to happen if you have set shared_memory_type
to sysv
. In that case, you can try starting the server with a smaller-than-normal number of buffers (shared_buffers), or reconfigure your kernel to increase the allowed shared memory size. You might also see this message when trying to start multiple servers on the same machine, if their total space requested exceeds the kernel limit.
An error like:
FATAL: could not create semaphores: No space left on device DETAIL: Failed system call was semget(5440126, 17, 03600).
does not mean you’ve run out of disk space. It means your kernel’s limit on the number of System V semaphores is smaller than the number PostgreSQL wants to create. As above, you might be able to work around the problem by starting the server with a reduced number of allowed connections (max_connections), but you’ll eventually want to increase the kernel limit.
Details about configuring System V IPC facilities are given in Section 18.4.1.
18.3.2. Client Connection Problems
Although the error conditions possible on the client side are quite varied and application-dependent, a few of them might be directly related to how the server was started. Conditions other than those shown below should be documented with the respective client application.
psql: could not connect to server: Connection refused Is the server running on host "server.joe.com" and accepting TCP/IP connections on port 5432?
This is the generic “I couldn’t find a server to talk to” failure. It looks like the above when TCP/IP communication is attempted. A common mistake is to forget to configure the server to allow TCP/IP connections.
Alternatively, you’ll get this when attempting Unix-domain socket communication to a local server:
psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"?
The last line is useful in verifying that the client is trying to connect to the right place. If there is in fact no server running there, the kernel error message will typically be either Connection refused
or No such file or directory
, as illustrated. (It is important to realize that Connection refused
in this context does not mean that the server got your connection request and rejected it. That case will produce a different message, as shown in Section 20.15.) Other error messages such as Connection timed out
might indicate more fundamental problems, like lack of network connectivity.
Before anyone can access the database, you must start the database server. The database server program is called postgres
.
If you are using a pre-packaged version of PostgreSQL, it almost certainly includes provisions for running the server as a background task according to the conventions of your operating system. Using the package’s infrastructure to start the server will be much less work than figuring out how to do this yourself. Consult the package-level documentation for details.
The bare-bones way to start the server manually is just to invoke postgres
directly, specifying the location of the data directory with the -D
option, for example:
$ postgres -D /usr/local/pgsql/data
which will leave the server running in the foreground. This must be done while logged into the PostgreSQL user account. Without -D
, the server will try to use the data directory named by the environment variable PGDATA
. If that variable is not provided either, it will fail.
Normally it is better to start postgres
in the background. For this, use the usual Unix shell syntax:
$ postgres -D /usr/local/pgsql/data >logfile 2>&1 &
It is important to store the server’s stdout and stderr output somewhere, as shown above. It will help for auditing purposes and to diagnose problems. (See Section 24.3 for a more thorough discussion of log file handling.)
The postgres
program also takes a number of other command-line options. For more information, see the postgres reference page and Chapter 19 below.
This shell syntax can get tedious quickly. Therefore the wrapper program pg_ctl is provided to simplify some tasks. For example:
pg_ctl start -l logfile
will start the server in the background and put the output into the named log file. The -D
option has the same meaning here as for postgres
. pg_ctl
is also capable of stopping the server.
Normally, you will want to start the database server when the computer boots. Autostart scripts are operating-system-specific. There are a few example scripts distributed with PostgreSQL in the contrib/start-scripts
directory. Installing one will require root privileges.
Different systems have different conventions for starting up daemons at boot time. Many systems have a file /etc/rc.local
or /etc/rc.d/rc.local
. Others use init.d
or rc.d
directories. Whatever you do, the server must be run by the PostgreSQL user account and not by root or any other user. Therefore you probably should form your commands using su postgres -c '...'
. For example:
su postgres -c 'pg_ctl start -D /usr/local/pgsql/data -l serverlog'
Here are a few more operating-system-specific suggestions. (In each case be sure to use the proper installation directory and user name where we show generic values.)
-
For FreeBSD, look at the file
contrib/start-scripts/freebsd
in the PostgreSQL source distribution. -
On OpenBSD, add the following lines to the file
/etc/rc.local
:if [ -x /usr/local/pgsql/bin/pg_ctl -a -x /usr/local/pgsql/bin/postgres ]; then su -l postgres -c '/usr/local/pgsql/bin/pg_ctl start -s -l /var/postgresql/log -D /usr/local/pgsql/data' echo -n ' postgresql' fi
-
On Linux systems either add
/usr/local/pgsql/bin/pg_ctl start -l logfile -D /usr/local/pgsql/data
to
/etc/rc.d/rc.local
or/etc/rc.local
or look at the filecontrib/start-scripts/linux
in the PostgreSQL source distribution.When using systemd, you can use the following service unit file (e.g., at
/etc/systemd/system/postgresql.service
):[Unit] Description=PostgreSQL database server Documentation=man:postgres(1) After=network-online.target Wants=network-online.target [Service] Type=notify User=postgres ExecStart=/usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data ExecReload=/bin/kill -HUP $MAINPID KillMode=mixed KillSignal=SIGINT TimeoutSec=infinity [Install] WantedBy=multi-user.target
Using
Type=notify
requires that the server binary was built withconfigure --with-systemd
.Consider carefully the timeout setting. systemd has a default timeout of 90 seconds as of this writing and will kill a process that does not report readiness within that time. But a PostgreSQL server that might have to perform crash recovery at startup could take much longer to become ready. The suggested value of
infinity
disables the timeout logic. -
On NetBSD, use either the FreeBSD or Linux start scripts, depending on preference.
-
On Solaris, create a file called
/etc/init.d/postgresql
that contains the following line:su - postgres -c "/usr/local/pgsql/bin/pg_ctl start -l logfile -D /usr/local/pgsql/data"
Then, create a symbolic link to it in
/etc/rc3.d
asS99postgresql
.
While the server is running, its PID is stored in the file postmaster.pid
in the data directory. This is used to prevent multiple server instances from running in the same data directory and can also be used for shutting down the server.
18.3.1. Server Start-up Failures
There are several common reasons the server might fail to start. Check the server’s log file, or start it by hand (without redirecting standard output or standard error) and see what error messages appear. Below we explain some of the most common error messages in more detail.
LOG: could not bind IPv4 address "127.0.0.1": Address already in use HINT: Is another postmaster already running on port 5432? If not, wait a few seconds and retry. FATAL: could not create any TCP/IP sockets
This usually means just what it suggests: you tried to start another server on the same port where one is already running. However, if the kernel error message is not Address already in use
or some variant of that, there might be a different problem. For example, trying to start a server on a reserved port number might draw something like:
$ postgres -p 666
LOG: could not bind IPv4 address "127.0.0.1": Permission denied
HINT: Is another postmaster already running on port 666? If not, wait a few seconds and retry.
FATAL: could not create any TCP/IP sockets
A message like:
FATAL: could not create shared memory segment: Invalid argument DETAIL: Failed system call was shmget(key=5440001, size=4011376640, 03600).
probably means your kernel’s limit on the size of shared memory is smaller than the work area PostgreSQL is trying to create (4011376640 bytes in this example). This is only likely to happen if you have set shared_memory_type
to sysv
. In that case, you can try starting the server with a smaller-than-normal number of buffers (shared_buffers), or reconfigure your kernel to increase the allowed shared memory size. You might also see this message when trying to start multiple servers on the same machine, if their total space requested exceeds the kernel limit.
An error like:
FATAL: could not create semaphores: No space left on device DETAIL: Failed system call was semget(5440126, 17, 03600).
does not mean you’ve run out of disk space. It means your kernel’s limit on the number of System V semaphores is smaller than the number PostgreSQL wants to create. As above, you might be able to work around the problem by starting the server with a reduced number of allowed connections (max_connections), but you’ll eventually want to increase the kernel limit.
Details about configuring System V IPC facilities are given in Section 18.4.1.
18.3.2. Client Connection Problems
Although the error conditions possible on the client side are quite varied and application-dependent, a few of them might be directly related to how the server was started. Conditions other than those shown below should be documented with the respective client application.
psql: could not connect to server: Connection refused Is the server running on host "server.joe.com" and accepting TCP/IP connections on port 5432?
This is the generic “I couldn’t find a server to talk to” failure. It looks like the above when TCP/IP communication is attempted. A common mistake is to forget to configure the server to allow TCP/IP connections.
Alternatively, you’ll get this when attempting Unix-domain socket communication to a local server:
psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"?
The last line is useful in verifying that the client is trying to connect to the right place. If there is in fact no server running there, the kernel error message will typically be either Connection refused
or No such file or directory
, as illustrated. (It is important to realize that Connection refused
in this context does not mean that the server got your connection request and rejected it. That case will produce a different message, as shown in Section 20.15.) Other error messages such as Connection timed out
might indicate more fundamental problems, like lack of network connectivity.
Прежде чем кто-либо сможет получить доступ к базе данных, вы должны запустить сервер базы данных. Программа сервера базы данных называется postgres
.
Если вы используете предварительно упакованную версию PostgreSQL,она почти наверняка включает в себя положения для запуска сервера в качестве фонового задания в соответствии с соглашениями вашей операционной системы.Использование инфраструктуры пакета для запуска сервера потребует гораздо меньше усилий,чем самостоятельное решение этой задачи.За подробностями обращайтесь к документации на уровне пакета.
Самый простой способ запустить сервер вручную — это просто вызвать postgres
напрямую, указав расположение каталога данных с помощью опции -D
, например:
$ postgres -D /usr/local/pgsql/data
что оставит сервер работающим на переднем плане. Это необходимо сделать, войдя в учетную запись пользователя PostgreSQL. Без -D
сервер попытается использовать каталог данных, названный переменной среды PGDATA
. Если эта переменная также не указана, произойдет сбой.
Обычно лучше запускать postgres
в фоновом режиме. Для этого используйте обычный синтаксис оболочки Unix:
$ postgres -D /usr/local/pgsql/data >logfile 2>&1 &
Важно где-нибудь хранить выходные данные сервера и stdout, как показано выше. Это поможет в целях аудита и диагностики проблем. (См. Раздел 25.3 для более подробного обсуждения обработки файлов журнала.)
Программа postgres
также принимает ряд других параметров командной строки. Для получения дополнительной информации см. справочную страницу postgres и главу 20 ниже.
Этот синтаксис оболочки может быстро стать утомительным. Поэтому программа-оболочка pg_ctl предназначена для упрощения некоторых задач. Например:
pg_ctl start -l logfile
запустит сервер в фоновом режиме и поместит результат в указанный файл журнала. Параметр -D
здесь имеет то же значение, что и для postgres
. pg_ctl
также может останавливать сервер.
Обычно вам нужно запускать сервер базы данных при загрузке компьютера. Сценарии автозапуска зависят от операционной системы. Есть несколько примеров сценариев, распространяемых с PostgreSQL в каталоге contrib/start-scripts
. Для его установки потребуются права root.
В разных системах существуют разные соглашения о запуске демонов во время загрузки. Во многих системах есть файл /etc/rc.local
или /etc/rc.d/rc.local
. Другие используют каталоги init.d
или rc.d
. Что бы вы ни делали, сервер должен запускаться под учетной записью пользователя PostgreSQL, а не под root или каким-либо другим пользователем. Поэтому вам, вероятно, следует формировать свои команды, используя su postgres -c '...'
. Например:
su postgres -c 'pg_ctl start -D /usr/local/pgsql/data -l serverlog'
Вот еще несколько специфических для операционной системы предложений.(В каждом случае убедитесь,что используете правильный каталог установки и имя пользователя,где мы показываем общие значения).
-
Для FreeBSD посмотрите файл
contrib/start-scripts/freebsd
в исходном дистрибутиве PostgreSQL. -
В OpenBSD добавьте следующие строки в файл
/etc/rc.local
:if [ -x /usr/local/pgsql/bin/pg_ctl -a -x /usr/local/pgsql/bin/postgres ]; then su -l postgres -c '/usr/local/pgsql/bin/pg_ctl start -s -l /var/postgresql/log -D /usr/local/pgsql/data' echo -n ' postgresql' fi
-
В системах Linux либо добавьте
/usr/local/pgsql/bin/pg_ctl start -l logfile -D /usr/local/pgsql/data
в
/etc/rc.d/rc.local
или/etc/rc.local
или просмотрите файлcontrib/start-scripts/linux
в дистрибутиве исходного кода PostgreSQL.При использовании systemd вы можете использовать следующий файл служебной единицы (например, в
/etc/systemd/system/postgresql.service
):[Unit] Description=PostgreSQL database server Documentation=man:postgres(1) [Service] Type=notify User=postgres ExecStart=/usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data ExecReload=/bin/kill -HUP $MAINPID KillMode=mixed KillSignal=SIGINT TimeoutSec=infinity [Install] WantedBy=multi-user.target
Использование
Type=notify
требует, чтобы двоичный файл сервера был собран с помощьюconfigure --with-systemd
.Внимательно рассмотрите настройку тайм-аута. На момент написания этой статьи systemd имеет тайм-аут по умолчанию 90 секунд и уничтожит процесс, который не сообщит о готовности в течение этого времени. Но серверу PostgreSQL, которому, возможно, придется выполнять аварийное восстановление при запуске, подготовка к работе может занять гораздо больше времени. Предлагаемое значение
infinity
отключает логику тайм-аута. -
На NetBSD используйте либо скрипты запуска FreeBSD,либо Linux,в зависимости от предпочтений.
-
В Solaris создайте файл с именем
/etc/init.d/postgresql
, содержащий следующую строку:su - postgres -c "/usr/local/pgsql/bin/pg_ctl start -l logfile -D /usr/local/pgsql/data"
Затем создайте на него символическую ссылку в
/etc/rc3.d
какS99postgresql
.
Пока сервер работает, его PID сохраняется в файле postmaster.pid
в каталоге данных. Это используется для предотвращения запуска нескольких экземпляров сервера в одном каталоге данных, а также может использоваться для выключения сервера.
19.3.1.Сбои при запуске сервера
Есть несколько распространенных причин,по которым сервер может не запуститься.Проверьте лог-файл сервера или запустите его вручную (без перенаправления стандартного вывода или стандартной ошибки)и посмотрите,какие сообщения об ошибках появляются.Ниже мы более подробно объясним некоторые из наиболее распространенных сообщений об ошибках.
LOG: could not bind IPv4 address "127.0.0.1": Address already in use HINT: Is another postmaster already running on port 5432? If not, wait a few seconds and retry. FATAL: could not create any TCP/IP sockets
Обычно это означает именно то, что он предлагает: вы пытались запустить другой сервер на том же порту, где он уже работает. Однако, если сообщение об ошибке ядра не « Address already in use
или какой-то его вариант, может быть другая проблема. Например, при попытке запустить сервер на зарезервированном номере порта может появиться что-то вроде:
$ postgres -p 666 LOG: could not bind IPv4 address "127.0.0.1": Permission denied HINT: Is another postmaster already running on port 666? If not, wait a few seconds and retry. FATAL: could not create any TCP/IP sockets
Сообщение вроде:
FATAL: could not create shared memory segment: Invalid argument DETAIL: Failed system call was shmget(key=5440001, size=4011376640, 03600).
вероятно, это означает, что ограничение вашего ядра на размер разделяемой памяти меньше, чем рабочая область, которую PostgreSQL пытается создать (4011376640 байт в этом примере). Это может произойти, только если вы установили shared_memory_type
на sysv
. В этом случае вы можете попробовать запустить сервер с меньшим, чем обычно, количеством буферов ( shared_buffers ) или перенастроить ядро, чтобы увеличить разрешенный размер разделяемой памяти. Вы также можете увидеть это сообщение при попытке запустить несколько серверов на одном компьютере, если их общее запрошенное пространство превышает ограничение ядра.
Ошибка типа..:
FATAL: could not create semaphores: No space left on device DETAIL: Failed system call was semget(5440126, 17, 03600).
вовсе не означает , что вы бежите из дискового пространства. Это означает, что ограничение вашего ядра на количество семафоров System V меньше, чем количество, которое PostgreSQL хочет создать. Как и выше, вы можете обойти проблему, запустив сервер с уменьшенным количеством разрешенных соединений ( max_connections ), но в конечном итоге вы захотите увеличить лимит ядра.
Подробная информация о настройке средств IPC System V приведена в Разделе 19.4.1 .
19.3.2.Проблемы с подключением клиента
Хотя возможные условия ошибок на стороне клиента довольно разнообразны и зависят от приложений,некоторые из них могут быть напрямую связаны с тем,как сервер был запущен.Условия,отличные от показанных ниже,должны быть задокументированы с соответствующим клиентским приложением.
psql: error: connection to server at "server.joe.com" (123.123.123.123), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections?
Это общий сбой «Я не смог найти сервер,с которым можно поговорить».Он выглядит как показано выше при попытке соединения по протоколу TCP/IP.Распространенная ошибка-забыть настроить сервер на разрешение TCP/IP-соединений.
В качестве альтернативы,вы можете получить это при попытке связи сокета Unix-домена с локальным сервером:
psql: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket?
Если сервер действительно работает, убедитесь, что представление клиента о пути к сокету (здесь /tmp
) согласуется с настройкой сервера unix_socket_directories .
В сообщении об ошибке подключения всегда отображается адрес сервера или путь к сокету, что полезно для проверки того, что клиент пытается подключиться к нужному месту. Если на самом деле сервер там не прослушивает, сообщение об ошибке ядра обычно будет либо В Connection refused
либо No such file or directory
, как показано. (Важно понимать, что Connection refused
в соединении в этом контексте не означает, что сервер получил ваш запрос на соединение и отклонил его. В этом случае будет выдано другое сообщение, как показано в Разделе 21.15 .) Другие сообщения об ошибках, такие как Connection timed out
может указывать на более серьезные проблемы, такие как отсутствие подключения к сети или брандмауэр, блокирующий подключение.
PostgreSQL
15.0
- F.40.5.3.Разрешения DDL
- SELinux определяет несколько разрешений для управления общими операциями для каждого типа объекта; такие как создание, изменение, удаление и перемаркировка безопасности Создание новых
- 19.5.Выключение сервера
- Существует несколько способов отключения сервера баз данных.
- 69.2.Встроенные классы операторов
- В основной дистрибутив PostgreSQL включены классы операторов SP-GiST,представленные в таблице 69.1.
- 69.5. Examples
- Исходный дистрибутив PostgreSQL включает несколько примеров классов индексных операторов для SP-GiST,описанных в таблице 69.1.
This is an idiosyncrasy of the systemd integration of PostgreSQL in Xenial.
The postgresql service unit installed by the postgresql-common package is just a dummy service which causes the actual service postgresql@9.6-main to be started via a dependency. You can see that dependency by running the command
systemctl list-dependencies postgresql
That dependency is not permanent, but generated during system boot by the systemd generator /lib/systemd/system-generators/postgresql-generator
which also comes with the postgresql-common package. The generator checks whether the startup mode in the file /etc/postgresql/9.6/main/start.conf
is set to auto
, and if so, sets up the dependency that subsequently causes instance 9.6-main to be started.
(More precisely, it checks all configuration subdirectories /etc/postgresql/*/*
and will create dependencies for all instances that are configured for automatic startup, but in a default installation there will be just the one instance.)
Due to the limitations of systemd generators (see man systemd.generator
) this process may fail, causing the dependencies to be absent after a reboot.
Systemd will then start only the dummy service, writing
systemd[1]: Starting PostgreSQL RDBMS...
systemd[1]: Started PostgreSQL RDBMS.
to the log but otherwise doing nothing.
Attempting to start the service manually by
systemctl start postgresql
will just reproduce that result.
Running the command
systemctl daemon-reload
manually as root will re-run the generator and in most cases fix the problem until the next reboot.
To solve the problem permanently you’ll have to find the reason why the generator fails during boot. Possible causes can be found in the systemd.generator manpage. In my case it was the PostgreSQL config file /etc/postgresql/9.6/main/postgresql.conf
which was symlinked to a different filesystem that wasn’t available yet when the generator ran early during boot. postgresql-generator
checks the existence of that file even though it doesn’t otherwise need it.
I have a problem to connect server for Postgres after I updated my windows.Before I update there is no problem to open the database. My database in Postgres also gone. When I want to create my new database it show this error:
Unable to connect to server: could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host «localhost» (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host «localhost» (127.0.0.1) and accepting TCP/IP connections on port 5432?
asked Nov 10, 2016 at 16:23
6
On windows, Just go to the ‘Services’. Start/Restart the postgresql-X64 service. It worked for me as my service was in stopped state somehow.
answered Feb 23, 2020 at 7:06
gagan chhabragagan chhabra
1,3151 gold badge8 silver badges9 bronze badges
4
There are two items to configure if your server isn’t on localhost:
- find your
postgresql.conf
and add your server’s public IP address to the end of the settinglisten_addresses
(separate multiple entries by commas); uncomment the line if it is commented out (e.g. with ‘#’) - add a line to
pg_hba.conf
containing your client’s IP address — you may copy the line containing 127.0.0.1 and change only the IP address
On Ubuntu, these files are in /etc/postgresql/<version>/main/
.
answered Mar 14, 2017 at 1:12
1
In my case I couldnt’ open the pgAdmin4, for some reason. I use Postgresql 10 and pgAdmin4
The port
in the postgresql.conf
was not the same as in the pgAdmin4 —> postgreSQL 10 —> properties —> Connection —> port.
I fixed it and it worked. Check if those 2 are in line.
answered Sep 12, 2020 at 13:55
2
First press win key+R
Search for services.msc
A window will open in that find postgresql-x64-13 and open that, in that tab click start option
For me its works perfectly.
answered May 31, 2021 at 5:03
VADHANVADHAN
2213 silver badges2 bronze badges
1
- Go to PgAdmin
- Right click on PostgreSQL
3.Choose properties - At the top, select connection
- Try changing the port from 5433 to 5432 or vice versa.
And re-enter.
answered May 15, 2021 at 17:27
1
Faced this problem immediately after installing on Windows. At startup the pgAdmin gave this error which means that the server is not running. For me the solution was: Start -> Control panel -> Administration -> Services -> postgresql-x64-12 — start or restart
answered Aug 7, 2020 at 21:49
Tim UzlovTim Uzlov
1712 silver badges6 bronze badges
On windows, Just go to the ‘Services’. Start/Restart the postgresql-X64 service. It worked for me as my service was in stopped state somehow.
worked for me
answered Sep 10, 2020 at 18:00
devyan91devyan91
791 silver badge6 bronze badges
This happened because I installed two versions of Postgres (v12 and v13). Psql 12 was installed later so got the port 5433. I needed to use Postgres 12. To fix this particular case:
-
Go to Program Files/Postgres/<required_version>/data
Open the
postgresql.conf
fileSearch for
Port
and change the port number to 5432. -
Open Windows Services (Press
Cmd + R
then typeservices.msc
) -
Stop the service for the version you don’t want (You can stop it permanentally from the Right Click > Properties menu.)
-
Start the service for the version you want.
answered Aug 7, 2021 at 14:30
Nitin NainNitin Nain
4,8721 gold badge38 silver badges51 bronze badges
I think the problem is with your server listening to default public IP address.
For example in the PostgreSQL package, your sever is set to listen to localhost as default public address which when you launch/ run database, the address might be something like ‘127.0.0.1’
To fix you can try change localhost to ‘‘ as in «listen_addresses = ‘‘».
As seen as "listen_addresses = 'localhost'"
under «Connection Settings
» in the postgresql.conf file
.
Also to access your postgresql.conf
file, go to:
On Windows, the file is in /Program Files/PostgreSQL/<version>/share/.
On Ubuntu, these files are in /etc/postgresql/<version>/main/.
P.S: Changing the defaults ‘localhost’; to ‘*’ will let your server listen to any public database address either «localhost, 127.0.0.1 etc.
I know you might have fix this, just for others that might run into the same issue in the future. Hope it was helpful
answered Jul 31, 2019 at 14:41
goto service and start postgresql-x64-10 service
steps
- run -> services.msc -> find postgresql-x64-10 -> start the service
- services image
answered Mar 12, 2021 at 14:33
This is a note for a normal user. If using an official installer, it should have a built-in service,
- Win+R and type
services.msc
- Search Postgres service based on the version installed, e.g., «
postgresql-x64-13 - PostgreSQL Server 13
« - Click stop, start, or restart the service option
- If you don’t see start/stop or if these buttons are disabled, then double-click on the PostgreSQL and change startup type to automatic and click on start. This will start the PostgreSQL every time automatically whenever you start your system.
answered Jul 6, 2021 at 2:54
Manoj SwamiManoj Swami
672 silver badges12 bronze badges
1
I had the same issue, so, I uninstalled postgres. And during reinstallation I noticed the error:
"Failed to load SQL modules into the database cluster"
And:
"Problem running post installation step.Installition may not complete correctly. Error reading file C:/Program Files/PostgreSQL/14/data/postgresql.conf"
.
I cancelled the installation and then tried again, but with a plain-text password this time, and it worked. It turned out that the special characters in my password were the problem.
ouflak
2,43810 gold badges43 silver badges49 bronze badges
answered Oct 1, 2021 at 14:48
Solutions:
-
Open
Services
and make sure thatpostgresql-x64-14
is running. -
Go to
C:Program FilesPostgreSQL14data
and openpostgresql.conf
with notepad, find and changeport
to e.g5432
and after that openServices
and restartpostgresql-x64-14
.
answered Apr 11, 2022 at 16:06
MaceMace
866 bronze badges
1
I got this error message when I moved my database to another computer.
I also got some error messages when starting the server first with
pg_ctl -D /wherever/your/database/is start
which were
pg_ctl: another server might be running; trying to start server anyway
server startingDETAIL: File «/wherever/your/database/is/PG_VERSION» does not contain valid data.
HINT: You might need to initdb.
In my case rather than running initdb this command actually fixed the issue
pg_ctl -D /wherever/your/database/is restart
answered May 10, 2018 at 13:42
uosjeaduosjead
4166 silver badges5 bronze badges
You might have changed the permissions of the ‘PostgreSQL 12’ in ‘services.msc’. Or maybe it is not started and you are trying to start the server when Postgre 12 is not running.
Try these:
- Try to start the ‘PostgreSQL 12’ in ‘services.msc’ manually.
- Try restarting your PC
- If nothing helps, try reinstalling PostgreSQL (pgAdmin 4) from the scratch.
answered Mar 30, 2021 at 12:18
Go to C:Program FilesPostgreSQL13data
, edit postgresql.conf
with notepad.
Change:
#port = 54XX
To:
port = 54XX
(change requires restart)
restart service at «service system» on window.
Tony Joseph
1,7822 gold badges16 silver badges17 bronze badges
answered Apr 20, 2021 at 17:54
When I run psql
, it gave me the same error, and it was because I changed the port while setting Postgres in the installation process.
I had to change back to the default port 5432 in PostgreSQL.conf (which can be found in the data directory) i.e
C:Program FilesPostgreSQL14data>
The problem is no more!
answered Jul 19, 2022 at 15:19
1
Using psql with single quotes fails:
psql -c 'Select version();' 'postgresql://username:password@db.abcdefghi.ap-southeast-2.rds.amazonaws.com:8080/the_db'
psql: could not connect to server: Connection refused
(0x0000274D/10061)
Is the server running on host «localhost» (::1) and accepting
TCP/IP connections on port 5432? could not connect to server: Connection refused (0x0000274D/10061)
Is the server running on host «localhost» (127.0.0.1) and accepting
TCP/IP connections on port 5432?
Using double quotes works:
psql -c "Select version();" "postgresql://username:password@db.abcdefghi.ap-southeast-2.rds.amazonaws.com:8080/the_db"
PostgreSQL 10.14 on x86_64-pc-linux-gnu, compiled by x86_64-unknown-linux-gnu-gcc (GCC) 4.9.4, 64-bit
(1 row)
answered Jul 14, 2021 at 1:40
Jeremy ThompsonJeremy Thompson
59.7k32 gold badges183 silver badges308 bronze badges
After a wasting 3-4 hrs i find the solution something like this
First set path in enviroment variable.And then make port and psql connecting same i.e 5432 or 5433
answered Sep 18, 2021 at 3:21
If you newly installed the pgAdmin
, and you did not remember to install PostgreSQL
at that time, you get that error. Make sure you install both pgAdmin
And PostgreSQL
.
answered Jan 6, 2022 at 11:14
For me I was getting this error and unable to open the server in PgAdmin is because I very often forgot to start the server, one for the way you can start the server with is by running this commands on cmd, make sure you provide the right path
cd "C:Program FilesPostgreSQL14bin"
pg_ctl -D "C:Program FilesPostgreSQL14data" start
answered Apr 13, 2022 at 6:42
DINA TAKLITDINA TAKLIT
5,8629 gold badges61 silver badges72 bronze badges
And so for the new arrivals. If you are using pgAdmin and a Windows operating system, do some research to resolve the issue.
Make sure you have Postgresql installed or active
-
To do this, go to windows services (press
Cmd + R
and run theservices.msc
command) -
Look in the list for a service called
postgresql-x{BIT}-{Version}-PostgreSQL Server {Version}
Solution 1: If you don’t find the service, then PostgreSQL is not installed or has been uninstalled, install it again.
Solution 2: If you find the service, but you still can’t log in, then most likely the service is not active for some reason, select the service and click the Start or Restart button
answered Mar 24, 2022 at 4:41
Harvey DentHarvey Dent
1,8763 gold badges8 silver badges15 bronze badges
Перед тем, как кто-нибудь сможет получить доступ к БД, Вы должны запустить сервер БД. Программа сервер называется postgres. Эта программа должна знать где найти необходимые ей для работы данные. Для этого используется опция -D. Так что самый простой способ запуска сервера:
$ postgres -D /usr/local/pgsql/data
В этом случае сервер будет запущен как активный процесс (не в фоне). Это должно быть сделано из под аккаунта пользователя PostgreSQL. Без опции -D сервер попытается найти данные в каталоге из переменной окружения PGDATA. Если же и этой переменной нет — то сервер не запустится.
Обычно гораздо удобнее запустить сервер в фоне. Для этого используйте обычный синтаксис оболочки Unix:
$ postgres -D /usr/local/pgsql/data >logfile 2>&1 &
Очень важно где-то хранить вывод сервера и вывод ошибок, как показано выше. Это поможет в диагностике проблем. (См раздел 23.3 где говорится об обработке лог файлов).
Программа postgres так же принимает опции командной строки. Более подробно об этом говорится в странице руководства postgres и в главе 18.
Однако эти команды оболочки могут быстро надоесть. Поэтому есть программа-обёртка pg_ctl, которая позволяет сделать всё то же самое, но гораздо проще. Например
pg_ctl start -l logfile
запустит фоновый процесс сервера и направит вывод в указаный файл. Опция -D здесь имеет то же значение. Кроме того, pg_ctl может и остановить сервер.
Обычно Вам нужно запустить сервер БД при загрузке компьютера. Скрипты для автозапуска зависят от системы. Некоторые варианты Вы можете найти в каталоге contrib/start-scripts. Для их установки могут потребоваться права суперпользователя.
Разные системы умеют разные условия для запуска демона при загрузке. Многие системы имеют файл /etc/rc.local или /etc/rc.d/rc.local. Другие системы используют каталоги init.d или rc.d. Как бы то ни было, сервер должен быть запущен от имени пользователя PostgreSQL, а не от имени суперпользователя или другого пользователя. Поэтому, возможно, Вы должны использовать такую форму команды su -c ‘…’ postgres. Например:
su -c ‘pg_ctl start -D /usr/local/pgsql/data -l serverlog’ postgres
Вот несколько предположений для разных ОС (В любом случае будьте уверены, что Вы указываете правильную папку установки и имя пользователя):
- FreeBSD смотрите на файл /contrib/start-scripts/freebsd в папке с исходниками
- OpenBSD добавьте следующие строки в /etc/rc.local
if [ -x /usr/local/pgsql/bin/pg_ctl -a -x /usr/local/pgsql/bin/postgres ];
then
su - -c '/usr/local/pgsql/bin/pg_ctl start -l /var/postgresql/log -s' postgres echo -n ' postgresql' fi
/usr/local/pgsql/bin/pg_ctl start -l logfile -D /usr/local/pgsql/data
su - postgres -c "/usr/local/pgsql/bin/pg_ctl start -l logfile -D /usr/local/pgsql/data"
Пока сервер запущен его PID хранится в postmaster.pid в каталоге с данными. Это используется для того, чтобы несколько экземпляров сервера не были запущены в одном и том же каталоге с данными. Его же можно использовать для остановки сервера.
17.3.1 Ошибки запуска сервера
Есть несколько общих ошибок из-за которых сервер может не запуститься. В поисках сообщения об ошибках обратитесь к логу сервера или запустите его вручную (без перенаправления стандартного вывода и вывода ошибок). Ниже мы объясним некоторые наиболее часто встречающиеся сообщения об ошибках:
LOG: could not bind IPv4 socket: Address already in use
HINT: Is another postmaster already running on port 5432? If not, wait a few seconds and retry.
FATAL: could not create TCP/IP listen socket
Обычно это значит именно то, что и написано: Вы пытаетесь запустить другой сервер на том же порту, на котором уже запущен другой сервер. Однако, если порт не используется, то причина может быть в другом. Например, попытка запустить сервер на зарезервированном порту тоже приведёт к похожей ошибке.
$ postgres -p 666
LOG: could not bind IPv4 socket: Permission denied
HINT: Is another postmaster already running on port 666? If not, wait a few seconds and retry.
FATAL: could not create TCP/IP listen socket
Сообщение вида
FATAL: could not create shared memory segment: Invalid argument
DETAIL: Failed system call was shmget (key=5440001, size=4011376640, 03600).
обычно означает, что предел разделяемой памяти ядра меньше, чем пытается создать рабочая область PostgreSQL (в нашем примере 4011376640 байт). Или это может значить что ваше ядро не сконфигурировано на поддержку разделяемой памяти в стиле System-V. В качестве «костыля» Вы можете попробовать запустить сервер с меньшим количеством буферов (shared_buffers). В конечном счёте Вы захотите переконфигурировать ядро для увеличения объёма разрешённой разделяемой памяти. Кроме того, Вы можете увидеть это сообщение в том случае, когда Вы пытаетесь запустить несколько экземпляров сервера на одной и той же машине, если их общие потребности в памяти превышают пределы ядра.
Ошибка вроде
FATAL: could not create semaphores: No space left on device
DETAIL: Failed system call was semget(5440126, 17, 03600).
не означает, что у Вас кончилось место на диске. Это означает, что лимит ядра на число System V семафоров меньше, чем то, сколько хочет создать PostgreSQL. Как и в предыдущем случае, можно воспользоваться «костылём» и запустить сервер с уменьшенным количеством разрешённых подключений (max_connections), но в конце концов Вы всё равно просто переконфигурируете своё ядро.
Если Вы получили ошибку «illegal system call«, то, скорее всего, разделяемая память и семафоры вообще не поддерживаются вашим ядром. В этом случае Вам остаётся только переконфигурировать ядро для включения поддержки этих возможностей.
Информация о том, как сконфигурировать возможности System V IPC находится в разделе 17.4.1
17.3.2 Проблемы с подключением клиента
Хотя ошибки подключения на стороне клиента имеют разные причины и зависят от конкретного приложения, тем не менее, некоторые из них связаны напрямую с тем, запущен ли сервер. Ошибки, отличные от приведённых ниже, должны решаться с конкретным приложением.
psql: could not connect to server: Connection refused
Is the server running on host «server.joe.com» and accepting
TCP/IP connections on port 5432?
Это стандартная ошибка «Я не могу найти сервер, с которым я должен говорить». Она похоже на ошибку выше про TCP/IP. Скорее всего сервер забыли настроить на приём TCP/IP соединений.
Кроме того, Вы можете увидеть такую ошибку при попытке соединиться с локальным сервером через unix сокеты:
psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket «/tmp/.s.PGSQL.5432»?
По последней строке Вы можете проверить, что клиент пытается подключиться туда, куда надо. Если там и правда нет сервера, то сообщение об ошибке от ядра будет либо Connection refused либо No such file or directory как в нашем примере. (Важно отметить, что Connection refused в данном случае не означает, что сервер получил ваш запрос на подключение и отклонил его. Такая ситуация приведёт к другому сообщению об ошибке, как показано в разделе 19.4). Другие сообщения об ошибках вроде Connection timed out могут означать наличие более серьёзных проблем, таких как задержки в сети.
I’m starting up a postgres 9.3 instance on a ubuntu 12.04 server :
~# service postgresql start
* The PostgreSQL server failed to start. Please check the log output.
[fail]
the start fails, but it leaves no log, this file is empty :
tail /var/log/postgresql/postgresql-9.3-main.log
and the are no other files in this directory : /var/log/postgresql/
what is the best way to troubleshoot this ?
asked Apr 7, 2014 at 16:31
6
Try running it manually with debug enabled. This will cause it to run in the foreground and print any error messages to standard error, while also increasing the verbosity.
I believe this will be the correct command line for PostgreSQL 9.3 on Ubuntu, but it might require some very slight tweaking (note: line is split for readability; you can recombine it to a single line (without the backslash) if you want):
/usr/lib/postgresql/9.3/bin/postgres -d 3 -D /var/lib/postgresql/9.3/main
-c config_file=/etc/postgresql/9.3/main/postgresql.conf
The beginning is the location of the postgres
binary, then we enable debug and set it to level 3 (you can adjust this up or down to increase or decrease verbosity). Next we specify the data directory and the config file to start with. These should be the defaults for Ubuntu Server 12.04, I think.
Hopefully, that’ll give you enough information to determine where the problem is.
answered Apr 7, 2014 at 19:01
6
Based on the answer of @christopher:
With postgres 12 on ubuntu, I ran:
# with my custom data dir:
/usr/lib/postgresql/12/bin/postgres -d 3 -D /media/ssd1/pg_data -c config_file=/etc/postgresql/12/main/postgresql.conf
# with default config:
/usr/lib/postgresql/12/bin/postgres -d 3 -D /var/lib/postgresql/12/main -c config_file=/etc/postgresql/12/main/postgresql.conf
In my case, the issue was the following:
2020-06-02 15:27:45.468 GMT [2522] LOG: skipping missing configuration file "/media/ssd1/pg_data/postgresql.auto.conf"
2020-06-02 17:27:45.469 CEST [2522] FATAL: data directory "/media/ssd1/pg_data" has wrong ownership
2020-06-02 17:27:45.469 CEST [2522] HINT: The server must be started by the user that owns the data directory.
2020-06-02 17:27:45.469 CEST [2522] DEBUG: shmem_exit(1): 0 before_shmem_exit callbacks to make
2020-06-02 17:27:45.469 CEST [2522] DEBUG: shmem_exit(1): 0 on_shmem_exit callbacks to make
2020-06-02 17:27:45.469 CEST [2522] DEBUG: proc_exit(1): 0 callbacks to make
2020-06-02 17:27:45.469 CEST [2522] DEBUG: exit(1)
I had no useful info in sudo cat /var/log/postgresql/postgresql-12-main.log
And sudo systemctl start postgresql
produced no output
answered Jun 2, 2020 at 15:30
1
Прежде чем кто-либо сможет получить доступ к базе данных, вы должны запустить сервер базы данных. Программа сервера базы данных называется postgres
.
Если вы используете предварительно упакованную версию PostgreSQL,она почти наверняка включает в себя положения для запуска сервера в качестве фонового задания в соответствии с соглашениями вашей операционной системы.Использование инфраструктуры пакета для запуска сервера потребует гораздо меньше усилий,чем самостоятельное решение этой задачи.За подробностями обращайтесь к документации на уровне пакета.
Самый простой способ запустить сервер вручную — это просто вызвать postgres
напрямую, указав расположение каталога данных с помощью опции -D
, например:
$ postgres -D /usr/local/pgsql/data
что оставит сервер работающим на переднем плане. Это необходимо сделать, войдя в учетную запись пользователя PostgreSQL. Без -D
сервер попытается использовать каталог данных, названный переменной среды PGDATA
. Если эта переменная также не указана, произойдет сбой.
Обычно лучше запускать postgres
в фоновом режиме. Для этого используйте обычный синтаксис оболочки Unix:
$ postgres -D /usr/local/pgsql/data >logfile 2>&1 &
Важно где-нибудь хранить выходные данные сервера и stdout, как показано выше. Это поможет в целях аудита и диагностики проблем. (См. Раздел 25.3 для более подробного обсуждения обработки файлов журнала.)
Программа postgres
также принимает ряд других параметров командной строки. Для получения дополнительной информации см. справочную страницу postgres и главу 20 ниже.
Этот синтаксис оболочки может быстро стать утомительным. Поэтому программа-оболочка pg_ctl предназначена для упрощения некоторых задач. Например:
pg_ctl start -l logfile
запустит сервер в фоновом режиме и поместит результат в указанный файл журнала. Параметр -D
здесь имеет то же значение, что и для postgres
. pg_ctl
также может останавливать сервер.
Обычно вам нужно запускать сервер базы данных при загрузке компьютера. Сценарии автозапуска зависят от операционной системы. Есть несколько примеров сценариев, распространяемых с PostgreSQL в каталоге contrib/start-scripts
. Для его установки потребуются права root.
В разных системах существуют разные соглашения о запуске демонов во время загрузки. Во многих системах есть файл /etc/rc.local
или /etc/rc.d/rc.local
. Другие используют каталоги init.d
или rc.d
. Что бы вы ни делали, сервер должен запускаться под учетной записью пользователя PostgreSQL, а не под root или каким-либо другим пользователем. Поэтому вам, вероятно, следует формировать свои команды, используя su postgres -c '...'
. Например:
su postgres -c 'pg_ctl start -D /usr/local/pgsql/data -l serverlog'
Вот еще несколько специфических для операционной системы предложений.(В каждом случае убедитесь,что используете правильный каталог установки и имя пользователя,где мы показываем общие значения).
-
Для FreeBSD посмотрите файл
contrib/start-scripts/freebsd
в исходном дистрибутиве PostgreSQL. -
В OpenBSD добавьте следующие строки в файл
/etc/rc.local
:if [ -x /usr/local/pgsql/bin/pg_ctl -a -x /usr/local/pgsql/bin/postgres ]; then su -l postgres -c '/usr/local/pgsql/bin/pg_ctl start -s -l /var/postgresql/log -D /usr/local/pgsql/data' echo -n ' postgresql' fi
-
В системах Linux либо добавьте
/usr/local/pgsql/bin/pg_ctl start -l logfile -D /usr/local/pgsql/data
в
/etc/rc.d/rc.local
или/etc/rc.local
или просмотрите файлcontrib/start-scripts/linux
в дистрибутиве исходного кода PostgreSQL.При использовании systemd вы можете использовать следующий файл служебной единицы (например, в
/etc/systemd/system/postgresql.service
):[Unit] Description=PostgreSQL database server Documentation=man:postgres(1) [Service] Type=notify User=postgres ExecStart=/usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data ExecReload=/bin/kill -HUP $MAINPID KillMode=mixed KillSignal=SIGINT TimeoutSec=infinity [Install] WantedBy=multi-user.target
Использование
Type=notify
требует, чтобы двоичный файл сервера был собран с помощьюconfigure --with-systemd
.Внимательно рассмотрите настройку тайм-аута. На момент написания этой статьи systemd имеет тайм-аут по умолчанию 90 секунд и уничтожит процесс, который не сообщит о готовности в течение этого времени. Но серверу PostgreSQL, которому, возможно, придется выполнять аварийное восстановление при запуске, подготовка к работе может занять гораздо больше времени. Предлагаемое значение
infinity
отключает логику тайм-аута. -
На NetBSD используйте либо скрипты запуска FreeBSD,либо Linux,в зависимости от предпочтений.
-
В Solaris создайте файл с именем
/etc/init.d/postgresql
, содержащий следующую строку:su - postgres -c "/usr/local/pgsql/bin/pg_ctl start -l logfile -D /usr/local/pgsql/data"
Затем создайте на него символическую ссылку в
/etc/rc3.d
какS99postgresql
.
Пока сервер работает, его PID сохраняется в файле postmaster.pid
в каталоге данных. Это используется для предотвращения запуска нескольких экземпляров сервера в одном каталоге данных, а также может использоваться для выключения сервера.
19.3.1.Сбои при запуске сервера
Есть несколько распространенных причин,по которым сервер может не запуститься.Проверьте лог-файл сервера или запустите его вручную (без перенаправления стандартного вывода или стандартной ошибки)и посмотрите,какие сообщения об ошибках появляются.Ниже мы более подробно объясним некоторые из наиболее распространенных сообщений об ошибках.
LOG: could not bind IPv4 address "127.0.0.1": Address already in use HINT: Is another postmaster already running on port 5432? If not, wait a few seconds and retry. FATAL: could not create any TCP/IP sockets
Обычно это означает именно то, что он предлагает: вы пытались запустить другой сервер на том же порту, где он уже работает. Однако, если сообщение об ошибке ядра не « Address already in use
или какой-то его вариант, может быть другая проблема. Например, при попытке запустить сервер на зарезервированном номере порта может появиться что-то вроде:
$ postgres -p 666 LOG: could not bind IPv4 address "127.0.0.1": Permission denied HINT: Is another postmaster already running on port 666? If not, wait a few seconds and retry. FATAL: could not create any TCP/IP sockets
Сообщение вроде:
FATAL: could not create shared memory segment: Invalid argument DETAIL: Failed system call was shmget(key=5440001, size=4011376640, 03600).
вероятно, это означает, что ограничение вашего ядра на размер разделяемой памяти меньше, чем рабочая область, которую PostgreSQL пытается создать (4011376640 байт в этом примере). Это может произойти, только если вы установили shared_memory_type
на sysv
. В этом случае вы можете попробовать запустить сервер с меньшим, чем обычно, количеством буферов ( shared_buffers ) или перенастроить ядро, чтобы увеличить разрешенный размер разделяемой памяти. Вы также можете увидеть это сообщение при попытке запустить несколько серверов на одном компьютере, если их общее запрошенное пространство превышает ограничение ядра.
Ошибка типа..:
FATAL: could not create semaphores: No space left on device DETAIL: Failed system call was semget(5440126, 17, 03600).
вовсе не означает , что вы бежите из дискового пространства. Это означает, что ограничение вашего ядра на количество семафоров System V меньше, чем количество, которое PostgreSQL хочет создать. Как и выше, вы можете обойти проблему, запустив сервер с уменьшенным количеством разрешенных соединений ( max_connections ), но в конечном итоге вы захотите увеличить лимит ядра.
Подробная информация о настройке средств IPC System V приведена в Разделе 19.4.1 .
19.3.2.Проблемы с подключением клиента
Хотя возможные условия ошибок на стороне клиента довольно разнообразны и зависят от приложений,некоторые из них могут быть напрямую связаны с тем,как сервер был запущен.Условия,отличные от показанных ниже,должны быть задокументированы с соответствующим клиентским приложением.
psql: error: connection to server at "server.joe.com" (123.123.123.123), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections?
Это общий сбой «Я не смог найти сервер,с которым можно поговорить».Он выглядит как показано выше при попытке соединения по протоколу TCP/IP.Распространенная ошибка-забыть настроить сервер на разрешение TCP/IP-соединений.
В качестве альтернативы,вы можете получить это при попытке связи сокета Unix-домена с локальным сервером:
psql: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket?
Если сервер действительно работает, убедитесь, что представление клиента о пути к сокету (здесь /tmp
) согласуется с настройкой сервера unix_socket_directories .
В сообщении об ошибке подключения всегда отображается адрес сервера или путь к сокету, что полезно для проверки того, что клиент пытается подключиться к нужному месту. Если на самом деле сервер там не прослушивает, сообщение об ошибке ядра обычно будет либо В Connection refused
либо No such file or directory
, как показано. (Важно понимать, что Connection refused
в соединении в этом контексте не означает, что сервер получил ваш запрос на соединение и отклонил его. В этом случае будет выдано другое сообщение, как показано в Разделе 21.15 .) Другие сообщения об ошибках, такие как Connection timed out
может указывать на более серьезные проблемы, такие как отсутствие подключения к сети или брандмауэр, блокирующий подключение.
PostgreSQL
15.0
-
F.40.5.3.Разрешения DDL
SELinux определяет несколько разрешений для управления общими операциями для каждого типа объекта; такие как создание, изменение, удаление и перемаркировка безопасности Создание новых
-
19.5.Выключение сервера
Существует несколько способов отключения сервера баз данных.
-
69.2.Встроенные классы операторов
В основной дистрибутив PostgreSQL включены классы операторов SP-GiST,представленные в таблице 69.1.
-
69.5. Examples
Исходный дистрибутив PostgreSQL включает несколько примеров классов индексных операторов для SP-GiST,описанных в таблице 69.1.
Имеется:
Ubuntu 16.04.1 LTS
root@Ubuntu-1604-xenial-64-minimal ~ # uname -r
4.4.0-47-generic
PostgreSQL 9.5
root@Ubuntu-1604-xenial-64-minimal ~ # service postgresql status
● postgresql.service - LSB: PostgreSQL RDBMS server
Loaded: loaded (/etc/init.d/postgresql; bad; vendor preset: enabled)
Active: active (exited) since Thu 2016-12-01 02:21:43 UTC; 3 days ago
Docs: man:systemd-sysv-generator(8)
Warning: Journal has been rotated since unit was started. Log output is incomplete or unavailable.
При попытке подключиться к СУБД:
root@Ubuntu-1604-xenial-64-minimal ~ # psql -h localhost -p 5432 -U postgres -W
Password for user postgres:
psql: could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
Далее немного подробностей по командам — пустая выдача
root@Ubuntu-1604-xenial-64-minimal ~ # netstat -pant | grep postgres
root@Ubuntu-1604-xenial-64-minimal ~ #
root@Ubuntu-1604-xenial-64-minimal ~ # sudo su - postgres -c psql
psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
root@Ubuntu-1604-xenial-64-minimal ~ # ps aux|grep postgres
root 29349 0.0 0.0 16976 936 pts/0 S+ 12:00 0:00 grep --color=auto postgres
less /etc/postgresql/9.5/main/postgresql.conf
# - Connection Settings -
listen_addresses = '*' # what IP address(es) to listen on;
# comma-separated list of addresses;
# defaults to 'localhost'; use '*' for all
# (change requires restart)
port = 5432 # (change requires restart)
max_connections = 100 # (change requires restart)
#superuser_reserved_connections = 3 # (change requires restart)
unix_socket_directories = '/var/run/postgresql' # comma-separated list of directories
# (change requires restart)
В БД есть нужные данные, поэтому снести и заново поставить просто не могу(
Случилось это при перезагрузке сервера.
Что же делать, как же быть? Как все это починить?