Как поменять порт postgresql
Перейти к содержимому

Как поменять порт postgresql

  • автор:

change pgsql port [duplicate]

I have currently an installed pgsql instance that is running on port 1486 . I want to change this port to 5433 , how should I proceed for this?

2 Answers 2

There should be a line in your postgresql.conf file that says:

The location of the file can vary depending on your install options. On Debian-based distros it is /etc/postgresql/8.3/main/

On Windows it is C:\Program Files\PostgreSQL\9.3\data

Don’t forget to sudo service postgresql restart for changes to take effect.

Установка и базовая настройка PostgreSQL в Windows 10

date30.08.2022
useritpro
directoryWindows 10, Windows Server 2016
commentsкомментариев 11

PostgreSQL — это бесплатная объектно-реляционная СУБД с мощным функционалом, который позволяет конкурировать с платными базами данных, такими как Microsoft SQL, Oracle. PostgreSQL поддерживает пользовательские данные, функции, операции, домены и индексы. В данной статье мы рассмотрим установку и краткий обзор по управлению базой данных PostgreSQL. Мы установим СУБД PostgreSQL в Windows 10, создадим новую базу, добавим в неё таблицы и настроим доступа для пользователей. Также мы рассмотрим основы управления PostgreSQL с помощью SQL shell и визуальной системы управления PgAdmin. Надеюсь эта статья станет хорошей отправной точкой для обучения работы с PostgreSQL и использованию ее в разработке и тестовых проектах.

Установка PostgreSQL 11 в Windows 10

Для установки PostgreSQL перейдите на сайт https://www.postgresql.org и скачайте последнюю версию дистрибутива для Windows, на сегодняшний день это версия PostgreSQL 11 (в 11 версии PostgreSQL поддерживаются только 64-х битные редакции Windows). После загрузки запустите инсталлятор.

где скачать PostgreSQL 11 для windows 10 x64

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

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

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

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

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

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

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

Нажимаете Далее, Далее, на этом установка PostgreSQL завершена.

Доступ к PostgreSQL по сети, правила файерволла

Чтобы разрешить сетевой доступ к вашему экземпляру PostgreSQL с других компьютеров, вам нужно создать правила в файерволе. Вы можете создать правило через командную строку или PowerShell.

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

netsh advfirewall firewall add rule name=»Postgre Port» dir=in action=allow protocol=TCP localport=5432

  • Где rule name – имя правила
  • Localport – разрешенный порт

Либо вы можете создать правило, разрешающее TCP/IP доступ к экземпляру PostgreSQL на порту 5432 с помощью PowerShell:

New-NetFirewallRule -Name ‘POSTGRESQL-In-TCP’ -DisplayName ‘PostgreSQL (TCP-In)’ -Direction Inbound -Enabled True -Protocol TCP -LocalPort 5432

После применения команды в брандмауэре Windows появится новое разрешающее правило для порта Postgres.

правила бранжмауэра для доступа к PostgreSQL по сети

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

Restart-Service -Name postgresql-x64-11

служба postgresql-x64-11

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

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

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

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

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

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

  • Проверка установленной версии СУБД: psql –V
  • Для создания новой базы данных воспользуйтесь утилитой createdb: createdb -U postgres testdb (где postgres суперпользователь, testdb новая база данных)Введите пароль суперпользователя. createdb -U postgres
  • Проверить список активных баз: Psql -U postgres –l (пароль) Psql -U postgres вывести список запушенных баз
  • С помощью инструмента createuser cоздадим нового пользователя: createuser –U postgres operator (где operator -имя нового пользователя) createuser –U postgres - создать пользователя
  • Предоставим пользователю привилегии суперпользователя (на практике этого делать не надо). Запустите интерактивную командную оболочку управления PostgreSQL (shell): psql –U postgres . С помощью SQL команды ALTER ROLE предоставим нужные права нашему пользователю: ALTER ROLE operator SUPERUSER CREATEROLE CREATEDB; . Мы предоставили пользователю права суперпользователя, права на создание ролей и баз данных.
  • Для выводы списка пользователей и ролей в СУБД выполните команду: \du

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

PgAdmin: Визуальный редактор для PostgresSQL

Редактор PgAdmin служит для упрощения управления базой данных PostgresSQL в понятном визуальном режиме.

По умолчанию все созданные базы хранятся в каталоге base по пути C:\Program Files\PostgreSQL\11\data\base.

Для каждой БД существует подкаталог внутри PGDATA/base, названный по OID базы данных в pg_database. Этот подкаталог по умолчанию является местом хранения файлов базы данных; в частности, там хранятся её системные каталоги. Каждая таблица и индекс хранятся в отдельном файле.

Для резервного копирования и восстановления лучше использовать инструмент Backup в панели инструментов Tools. Для автоматизации бэкапа PostgreSQL из командной строки используйте утилиту pg_dump.exe.

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

Для написания SQL запросов в удобном графическом редакторе используется встроенный в pgAdmin инструмент Query Tool. Например, вы хотите создать новую таблицу в базе данных через инструмент Query Tool.

  • Выберите базу данных, в панели Tools откройте Query Tool
  • Создадим таблицу сотрудников:

CREATE TABLE employee
(
Id SERIAL PRIMARY KEY,
FirstName CHARACTER VARYING(30),
LastName CHARACTER VARYING(30),
Email CHARACTER VARYING(30),
Age INTEGER
);

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

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

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

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

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

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

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

Customize PostgreSQL port on Linux

Changing PostgreSQL port is our adventure in this article, hence, flow these instructions to achieve the objective in clear four steps.

If you didn’t have an adventure with PostgreSQL, then read this basics article.

PostgreSQL also called Postgres is a powerful DBMS. moreover, It is available in most Linux distributions. therefore, It comes with the default values.

I usually ask a few questions about any new software installation. for example, I ask what is the default values and where is the location of configuration files.

Postgres default port

PostgresSQL default port is 5432, however, the installer will pick the next available port if it is not available. for example port 5433 … etc.

Postgres default installation does not allow external access. hence, local applications use a socket or network port is 5432 from localhost only.

To check the current port used by Postgres service by using “netstat”. in default configuration, it will show you the port mapped to localhost 127.0.0.1:5434

netstat -lnp | grep postgres

changing Postgres default port

Open postgres main configuration file postgresql.conf. This file located inside /etc/postgresql//main/ . To clarify, PGVersion will replaced by postgresSQL version.

Changing port for postgresSQL 9.5

To successfully change database port the following steps Stop database if running by executing the following command

Как поменять порт postgresql

Specifies the TCP/IP address(es) on which the server is to listen for connections from client applications. The value takes the form of a comma-separated list of host names and/or numeric IP addresses. The special entry * corresponds to all available IP interfaces. The entry 0.0.0.0 allows listening for all IPv4 addresses and :: allows listening for all IPv6 addresses. If the list is empty, the server does not listen on any IP interface at all, in which case only Unix-domain sockets can be used to connect to it. The default value is localhost , which allows only local TCP/IP “ loopback ” connections to be made. While client authentication (Chapter 21) allows fine-grained control over who can access the server, listen_addresses controls which interfaces accept connection attempts, which can help prevent repeated malicious connection requests on insecure network interfaces. This parameter can only be set at server start.

The TCP port the server listens on; 5432 by default. Note that the same port number is used for all IP addresses the server listens on. This parameter can only be set at server start.

Determines the maximum number of concurrent connections to the database server. The default is typically 100 connections, but might be less if your kernel settings will not support it (as determined during initdb ). This parameter can only be set at server start.

When running a standby server, you must set this parameter to the same or higher value than on the primary server. Otherwise, queries will not be allowed in the standby server.

Determines the number of connection “ slots ” that are reserved for connections by PostgreSQL superusers. At most max_connections connections can ever be active simultaneously. Whenever the number of active concurrent connections is at least max_connections minus superuser_reserved_connections , new connections will be accepted only for superusers, and no new replication connections will be accepted.

The default value is three connections. The value must be less than max_connections . This parameter can only be set at server start.

Specifies the directory of the Unix-domain socket(s) on which the server is to listen for connections from client applications. Multiple sockets can be created by listing multiple directories separated by commas. Whitespace between entries is ignored; surround a directory name with double quotes if you need to include whitespace or commas in the name. An empty value specifies not listening on any Unix-domain sockets, in which case only TCP/IP sockets can be used to connect to the server.

A value that starts with @ specifies that a Unix-domain socket in the abstract namespace should be created (currently supported on Linux only). In that case, this value does not specify a “ directory ” but a prefix from which the actual socket name is computed in the same manner as for the file-system namespace. While the abstract socket name prefix can be chosen freely, since it is not a file-system location, the convention is to nonetheless use file-system-like values such as @/tmp .

The default value is normally /tmp , but that can be changed at build time. On Windows, the default is empty, which means no Unix-domain socket is created by default. This parameter can only be set at server start.

In addition to the socket file itself, which is named .s.PGSQL. nnnn where nnnn is the server’s port number, an ordinary file named .s.PGSQL. nnnn .lock will be created in each of the unix_socket_directories directories. Neither file should ever be removed manually. For sockets in the abstract namespace, no lock file is created.

Sets the owning group of the Unix-domain socket(s). (The owning user of the sockets is always the user that starts the server.) In combination with the parameter unix_socket_permissions this can be used as an additional access control mechanism for Unix-domain connections. By default this is the empty string, which uses the default group of the server user. This parameter can only be set at server start.

This parameter is not supported on Windows. Any setting will be ignored. Also, sockets in the abstract namespace have no file owner, so this setting is also ignored in that case.

Sets the access permissions of the Unix-domain socket(s). Unix-domain sockets use the usual Unix file system permission set. The parameter value is expected to be a numeric mode specified in the format accepted by the chmod and umask system calls. (To use the customary octal format the number must start with a 0 (zero).)

The default permissions are 0777 , meaning anyone can connect. Reasonable alternatives are 0770 (only user and group, see also unix_socket_group ) and 0700 (only user). (Note that for a Unix-domain socket, only write permission matters, so there is no point in setting or revoking read or execute permissions.)

This access control mechanism is independent of the one described in Chapter 21.

This parameter can only be set at server start.

This parameter is irrelevant on systems, notably Solaris as of Solaris 10, that ignore socket permissions entirely. There, one can achieve a similar effect by pointing unix_socket_directories to a directory having search permission limited to the desired audience.

Sockets in the abstract namespace have no file permissions, so this setting is also ignored in that case.

Enables advertising the server’s existence via Bonjour . The default is off. This parameter can only be set at server start.

Specifies the Bonjour service name. The computer name is used if this parameter is set to the empty string » (which is the default). This parameter is ignored if the server was not compiled with Bonjour support. This parameter can only be set at server start.

Specifies the amount of time with no network activity after which the operating system should send a TCP keepalive message to the client. If this value is specified without units, it is taken as seconds. A value of 0 (the default) selects the operating system’s default. This parameter is supported only on systems that support TCP_KEEPIDLE or an equivalent socket option, and on Windows; on other systems, it must be zero. In sessions connected via a Unix-domain socket, this parameter is ignored and always reads as zero.

On Windows, setting a value of 0 will set this parameter to 2 hours, since Windows does not provide a way to read the system default value.

Specifies the amount of time after which a TCP keepalive message that has not been acknowledged by the client should be retransmitted. If this value is specified without units, it is taken as seconds. A value of 0 (the default) selects the operating system’s default. This parameter is supported only on systems that support TCP_KEEPINTVL or an equivalent socket option, and on Windows; on other systems, it must be zero. In sessions connected via a Unix-domain socket, this parameter is ignored and always reads as zero.

On Windows, setting a value of 0 will set this parameter to 1 second, since Windows does not provide a way to read the system default value.

Specifies the number of TCP keepalive messages that can be lost before the server’s connection to the client is considered dead. A value of 0 (the default) selects the operating system’s default. This parameter is supported only on systems that support TCP_KEEPCNT or an equivalent socket option; on other systems, it must be zero. In sessions connected via a Unix-domain socket, this parameter is ignored and always reads as zero.

This parameter is not supported on Windows, and must be zero.

Specifies the amount of time that transmitted data may remain unacknowledged before the TCP connection is forcibly closed. If this value is specified without units, it is taken as milliseconds. A value of 0 (the default) selects the operating system’s default. This parameter is supported only on systems that support TCP_USER_TIMEOUT ; on other systems, it must be zero. In sessions connected via a Unix-domain socket, this parameter is ignored and always reads as zero.

This parameter is not supported on Windows, and must be zero.

Sets the time interval between optional checks that the client is still connected, while running queries. The check is performed by polling the socket, and allows long running queries to be aborted sooner if the kernel reports that the connection is closed.

This option relies on kernel events exposed by Linux, macOS, illumos and the BSD family of operating systems, and is not currently available on other systems.

If the value is specified without units, it is taken as milliseconds. The default value is 0 , which disables connection checks. Without connection checks, the server will detect the loss of the connection only at the next interaction with the socket, when it waits for, receives or sends data.

For the kernel itself to detect lost TCP connections reliably and within a known timeframe in all scenarios including network failure, it may also be necessary to adjust the TCP keepalive settings of the operating system, or the tcp_keepalives_idle, tcp_keepalives_interval and tcp_keepalives_count settings of PostgreSQL .

20.3.2. Authentication

Maximum amount of time allowed to complete client authentication. If a would-be client has not completed the authentication protocol in this much time, the server closes the connection. This prevents hung clients from occupying a connection indefinitely. If this value is specified without units, it is taken as seconds. The default is one minute ( 1m ). This parameter can only be set in the postgresql.conf file or on the server command line.

When a password is specified in CREATE ROLE or ALTER ROLE , this parameter determines the algorithm to use to encrypt the password. Possible values are scram-sha-256 , which will encrypt the password with SCRAM-SHA-256, and md5 , which stores the password as an MD5 hash. The default is scram-sha-256 .

Note that older clients might lack support for the SCRAM authentication mechanism, and hence not work with passwords encrypted with SCRAM-SHA-256. See Section 21.5 for more details.

Sets the location of the server’s Kerberos key file. The default is FILE:/usr/local/pgsql/etc/krb5.keytab (where the directory part is whatever was specified as sysconfdir at build time; use pg_config —sysconfdir to determine that). If this parameter is set to an empty string, it is ignored and a system-dependent default is used. This parameter can only be set in the postgresql.conf file or on the server command line. See Section 21.6 for more information.

Sets whether GSSAPI user names should be treated case-insensitively. The default is off (case sensitive). This parameter can only be set in the postgresql.conf file or on the server command line.

This parameter enables per-database user names. It is off by default. This parameter can only be set in the postgresql.conf file or on the server command line.

If this is on, you should create users as username@dbname . When username is passed by a connecting client, @ and the database name are appended to the user name and that database-specific user name is looked up by the server. Note that when you create users with names containing @ within the SQL environment, you will need to quote the user name.

With this parameter enabled, you can still create ordinary global users. Simply append @ when specifying the user name in the client, e.g., joe@ . The @ will be stripped off before the user name is looked up by the server.

db_user_namespace causes the client’s and server’s user name representation to differ. Authentication checks are always done with the server’s user name so authentication methods must be configured for the server’s user name, not the client’s. Because md5 uses the user name as salt on both the client and server, md5 cannot be used with db_user_namespace .

This feature is intended as a temporary measure until a complete solution is found. At that time, this option will be removed.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *