- TablePlus
- How to start and stop PostgreSQL server?
- PostgreSQL 9.2 Начало!
- Сборка и установка
- Настройка
- Утилиты для работы с базой
- Менеджеры по работе с базой
- Start postgres in linux
- 18.3.1. Server Start-up Failures
- 18.3.2. Client Connection Problems
- Submit correction
- 17.3. Starting the Database Server
- 17.3.1. Server Start-up Failures
- 17.3.2. Client Connection Problems
TablePlus
How to start and stop PostgreSQL server?
October 30, 2018
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 PostgreSQL server now and relaunch at login:
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:
- 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
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:
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.
Источник
PostgreSQL 9.2 Начало!
Мне хотелось создать прекрасный объемлющий мануал Getting Start без всякой воды, но включающий основные плюшки для начинающих по системе PostgreSQL в Linux.
PostgreSQL является объектно-реляционной системой управления базами данных (ОРСУБД) на основе POSTGRES, версия 4.2, разработанной в Университете Калифорнии в Беркли департаменте компьютерных наук.
PostgreSQL является open source потомком оригинального кода Berkeley. Он поддерживает большую часть стандарта SQL и предлагает множество современных функций:
Сборка и установка
Как и все любители мейнстрима PostgreSQL мы будем конечно же собирать, а не скачивать готовые пакеты (в репозитариях Debian, например, нет последней версии). Вот здесь лежит множество версий, скачивать конечно же лучше всего последнюю. На момент написания поста это версия 9.2.2
Теперь у нас есть директория с исходниками сей прекрасной базы данных.
По умолчанию файлы базы будут установлены в директорию /usr/local/pgsql, но эту директорию можно изменить задав
перед командой ./configure
Перед сборкой можно указать компилятор С++
PostgeSQL может использовать readline библиотеку, если у вас её нет и нет желания её ставить просто укажите опцию
Надеюсь у всех есть Autotools? Тогда вперед к сборке:
Все господа! Поздравляю!
Настройка
Нам необходимо указать хранилище данных наших баз данных (кластер) и запустить её.
Есть один нюанс — владельцем директории данных и пользователь, который может запускать базу должен быть не root. Это сделано в целях безопасности системы. Поэтому создадим специального пользователя
И далее все понятно
Важный процесс. Мы должны инициализировать кластер баз дынных. Сделать мы должны это от имени пользователя postgres
Теперь нужно добавить запуск PostgreSQL в автостарт. Для этого существует уже готовый скрипт и лежит он в postgresql-9.2.2/contrib/start-scripts/linux
Этот файл можно открыть и обратить внимание на следующие переменные:
- prefix — это место куда мы ставили PostgreSQL и задавали в ./configure
- PGDATA — это то, где хранится кластер баз данных и куда должен иметь доступ наш пользователь postgres
- PGUSER — это тот самый пользователь, от лица которого будет все работать
Если все стоит верно, то добвляем наш скрипт в init.d
Перезапускам систему, чтобы проверить что наш скрипт работает.
Вводим
И если появится окно работы с базой, то настройка прошла успешно! Поздравляю!
По умолчанию создается база данных с именем postgres
Теперь важно поговорить о методах авторизации.
В /usr/local/pgsql/data/pg_hba.conf как раз есть необходимые для этого настройка
Первая строка отвечает за локальное соединение, вторая — за соединение про протоколу IPv4, а третья по протоколу IPv6.
Самый последний параметр — это как раз таки метод авторизации. Его и рассмотрим (только основные)
- trust — доступ к базе может получить кто угодно под любым именем, имеющий с ней соединение.
- reject — отклонить безоговорочно! Это подходит для фильтрации определенных IP адресов
- password — требует обязательного ввода пароля. Не подходит для локальных пользователей, только пользователи созданные командой CREATE USER
- ident — позволяет только пользователем зарегистрированным в файле /usr/local/pgsql/data/pg_ident.conf устанавливать соединение с базой.
Вкратце расскажу об основных утилитах, которые пригодятся в работе.
Утилиты для работы с базой
pg_config
Возвращает информацию о текущей установленной версии PostgreSQL.
initdb
Инициализирует новое хранилище данных (кластер баз данных). Кластер представляет собой совокупность баз данных управляемых одним экземпляром севера. initdb должен быть запущен от имени будущего владельца сервера (как указано выше от имени postgres).
pg_ctl
Управляет процессом работы сервера PostgreSQL. Позволяет запускать, выполнять перезапуск, останавливать работу сервера, указать лог файл и другое.
psql
Клиент для работы с базой дынных. Позволяет выполнять SQL операции.
createdb
dropdb
Удаляет базу данных. Является оберткой SQL команды DROP DATABASE.
createuser
dropuser
Удаляет пользователя базы данных. Является оберткой SQL команды DROP ROLE.
createlang
droplang
Удаляет язык программирования. Является оберткой SQL команды DROP LANGUAGE.
pg_dump
pg_restore
pg_dumpall
Создает бэкап (дамп) всего кластера в файл.
reindexdb
Производит переиндексацию базы данных. Является оберткой SQL команды REINDEX.
clusterdb
Производит перекластеризацию таблиц в базе данных. Является оберткой SQL команды CLUSTER.
vacuumdb
Сборщик мусора и оптимизатор базы данных. Является оберткой SQL команды VACUUM.
Менеджеры по работе с базой
Что касается менеджера по работа с базой, то есть php менеджер — это phpPgAdmin и GUI менеджер pgAdmin. Должен заметить, что они оба плохо поддерживают последнюю версию PostgreSQL.
Источник
Start postgres in linux
Before anyone can access the database, you must start the database server. The database server program is called postgres . The postgres program must know where to find the data it is supposed to use. This is done with the -D option. Thus, the simplest way to start the server is:
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:
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:
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 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:
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 :
On Linux systems either add
to /etc/rc.d/rc.local or /etc/rc.local or look at the file contrib/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 ):
Using Type=notify requires that the server binary was built with configure —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 notify 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 0 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:
Then, create a symbolic link to it in /etc/rc3.d as S99postgresql .
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.
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:
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). Or it could mean that you do not have System-V-style shared memory support configured into your kernel at all. As a temporary workaround, you can try starting the server with a smaller-than-normal number of buffers (shared_buffers). You will eventually want to 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.
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.
If you get an “ illegal system call ” error, it is likely that shared memory or semaphores are not supported in your kernel at all. In that case your only option is to reconfigure the kernel to enable these features.
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.
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:
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.4.) Other error messages such as Connection timed out might indicate more fundamental problems, like lack of network connectivity.
Prev | Up | Next |
18.2. Creating a Database Cluster | Home | 18.4. Managing Kernel Resources |
Submit correction
If you see anything in the documentation that is not correct, does not match your experience with the particular feature or requires further clarification, please use this form to report a documentation issue.
Copyright © 1996-2021 The PostgreSQL Global Development Group
Источник
17.3. Starting the Database Server
Before anyone can access the database, you must start the database server. The database server program is called postgres. The postgres program must know where to find the data it is supposed to use. This is done with the -D option. Thus, the simplest way to start the server is:
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:
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 23.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 18 below.
This shell syntax can get tedious quickly. Therefore the wrapper program pg_ctl is provided to simplify some tasks. For example:
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 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:
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:
On Linux systems either add
to /etc/rc.d/rc.local or /etc/rc.local or look at the file contrib/start-scripts/linux in the PostgreSQL source distribution.
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:
Then, create a symbolic link to it in /etc/rc3.d as S99postgresql.
17.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.
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:
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). Or it could mean that you do not have System-V-style shared memory support configured into your kernel at all. As a temporary workaround, you can try starting the server with a smaller-than-normal number of buffers (shared_buffers). You will eventually want to 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.
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.
If you get an «illegal system call» error, it is likely that shared memory or semaphores are not supported in your kernel at all. In that case your only option is to reconfigure the kernel to enable these features.
17.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.
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:
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 19.4.) Other error messages such as Connection timed out might indicate more fundamental problems, like lack of network connectivity.
Источник