: :

ПнВтСрЧтПтСбВс

2017-11-20 13:21:49 15033 2

Установка и первоначальная настройка Postgresql из исходников на Ubuntu 16.04

Произведем установку и первоначальную настройку СУБД Postgresql из исходных кодов на ОС Ubuntu 16.04. Для сборки возьмем версию Postgresql-9.6.5

Скачаем исходные коды Postgresql с официального сайта в директорию /usr/src:

cd /usr/src

wget https://ftp.postgresql.org/pub/source/v9.6.5/postgresql-9.6.5.tar.gz

Разархивируем архим с файлами:

tar xzf postgresql-9.6.5.tar.gz

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

cd postgresql-9.6.5

Выведем все возможные опции для сборки пакета:

sudo ./configure --help

`configure" configures PostgreSQL 9.6.5 to adapt to many kinds of systems.

Usage: ./configure [OPTION]... [VAR=VALUE]...

To assign environment variables (e.g., CC, CFLAGS...), specify them as
VAR=VALUE.  See below for descriptions of some of the useful variables.

Defaults for the options are specified in brackets.

Configuration:
  -h, --help              display this help and exit
      --help=short        display options specific to this package
      --help=recursive    display the short help of all the included packages
  -V, --version           display version information and exit
  -q, --quiet, --silent   do not print `checking ..." messages
      --cache-file=FILE   cache test results in FILE [disabled]
  -C, --config-cache      alias for `--cache-file=config.cache"
  -n, --no-create         do not create output files
      --srcdir=DIR        find the sources in DIR [configure dir or `.."]

Installation directories:
  --prefix=PREFIX         install architecture-independent files in PREFIX
                          [/usr/local/pgsql]
  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
                          [PREFIX]

By default, `make install" will install all the files in
`/usr/local/pgsql/bin", `/usr/local/pgsql/lib" etc.  You can specify
an installation prefix other than `/usr/local/pgsql" using `--prefix",
for instance `--prefix=$HOME".

For better control, use the options below.

Fine tuning of the installation directories:
  --bindir=DIR            user executables [EPREFIX/bin]
  --sbindir=DIR           system admin executables [EPREFIX/sbin]
  --libexecdir=DIR        program executables [EPREFIX/libexec]
  --sysconfdir=DIR        read-only single-machine data [PREFIX/etc]
  --sharedstatedir=DIR    modifiable architecture-independent data [PREFIX/com]
  --localstatedir=DIR     modifiable single-machine data [PREFIX/var]
  --libdir=DIR            object code libraries [EPREFIX/lib]
  --includedir=DIR        C header files [PREFIX/include]
  --oldincludedir=DIR     C header files for non-gcc [/usr/include]
  --datarootdir=DIR       read-only arch.-independent data root [PREFIX/share]
  --datadir=DIR           read-only architecture-independent data [DATAROOTDIR]
  --infodir=DIR           info documentation [DATAROOTDIR/info]
  --localedir=DIR         locale-dependent data [DATAROOTDIR/locale]
  --mandir=DIR            man documentation [DATAROOTDIR/man]
  --docdir=DIR            documentation root [DATAROOTDIR/doc/postgresql]
  --htmldir=DIR           html documentation [DOCDIR]
  --dvidir=DIR            dvi documentation [DOCDIR]
  --pdfdir=DIR            pdf documentation [DOCDIR]
  --psdir=DIR             ps documentation [DOCDIR]

System types:
  --build=BUILD     configure for building on BUILD [guessed]
  --host=HOST       cross-compile to build programs to run on HOST [BUILD]

Optional Features:
  --disable-option-checking  ignore unrecognized --enable/--with options
  --disable-FEATURE       do not include FEATURE (same as --enable-FEATURE=no)
  --enable-FEATURE[=ARG]  include FEATURE [ARG=yes]
  --disable-integer-datetimes
                          disable 64-bit integer date/time support
  --enable-nls[=LANGUAGES]
                          enable Native Language Support
  --disable-rpath         do not embed shared library search path in
                          executables
  --disable-spinlocks     do not use spinlocks
  --disable-atomics       do not use atomic operations
  --enable-debug          build with debugging symbols (-g)
  --enable-profiling      build with profiling enabled
  --enable-coverage       build with coverage testing instrumentation
  --enable-dtrace         build with DTrace support
  --enable-tap-tests      enable TAP tests (requires Perl and IPC::Run)
  --enable-depend         turn on automatic dependency tracking
  --enable-cassert        enable assertion checks (for debugging)
  --disable-thread-safety disable thread-safety in client libraries
  --disable-largefile     omit support for large files
  --disable-float4-byval  disable float4 passed by value
  --disable-float8-byval  disable float8 passed by value

Optional Packages:
  --with-PACKAGE[=ARG]    use PACKAGE [ARG=yes]
  --without-PACKAGE       do not use PACKAGE (same as --with-PACKAGE=no)
  --with-extra-version=STRING
                          append STRING to version
  --with-template=NAME    override operating system template
  --with-includes=DIRS    look for additional header files in DIRS
  --with-libraries=DIRS   look for additional libraries in DIRS
  --with-libs=DIRS        alternative spelling of --with-libraries
  --with-pgport=PORTNUM   set default port number [5432]
  --with-blocksize=BLOCKSIZE
                          set table block size in kB [8]
  --with-segsize=SEGSIZE  set table segment size in GB [1]
  --with-wal-blocksize=BLOCKSIZE
                          set WAL block size in kB [8]
  --with-wal-segsize=SEGSIZE
                          set WAL segment size in MB [16]
  --with-CC=CMD           set compiler (deprecated)
  --with-tcl              build Tcl modules (PL/Tcl)
  --with-tclconfig=DIR    tclConfig.sh is in DIR
  --with-perl             build Perl modules (PL/Perl)
  --with-python           build Python modules (PL/Python)
  --with-gssapi           build with GSSAPI support
  --with-krb-srvnam=NAME  default service principal name in Kerberos (GSSAPI)
                          [postgres]
  --with-pam              build with PAM support
  --with-bsd-auth         build with BSD Authentication support
  --with-ldap             build with LDAP support
  --with-bonjour          build with Bonjour support
  --with-openssl          build with OpenSSL support
  --with-selinux          build with SELinux support
  --with-systemd          build with systemd support
  --without-readline      do not use GNU Readline nor BSD Libedit for editing
  --with-libedit-preferred
                          prefer BSD Libedit over GNU Readline
  --with-uuid=LIB         build contrib/uuid-ossp using LIB (bsd,e2fs,ossp)
  --with-ossp-uuid        obsolete spelling of --with-uuid=ossp
  --with-libxml           build with XML support
  --with-libxslt          use XSLT support when building contrib/xml2
  --with-system-tzdata=DIR
                          use system time zone data in DIR
  --without-zlib          do not use Zlib
  --with-gnu-ld           assume the C compiler uses GNU ld [default=no]

Some influential environment variables:
  CC          C compiler command
  CFLAGS      C compiler flags
  LDFLAGS     linker flags, e.g. -L if you have libraries in a
              nonstandard directory 
  LIBS        libraries to pass to the linker, e.g. -l
  CPPFLAGS    (Objective) C/C++ preprocessor flags, e.g. -I if
              you have headers in a nonstandard directory 
  CPP         C preprocessor
  LDFLAGS_EX  extra linker flags for linking executables only
  LDFLAGS_SL  extra linker flags for linking shared libraries only
  DOCBOOKSTYLE
              location of DocBook stylesheets

Use these variables to override the choices made by `configure" or to help
it to find libraries and programs with nonstandard names/locations.

Выбираем необходимые и добавляем их как опции при сборке.

Запускаем скрипт для конфигурирования сборки (собирать будем с поддержкой systemd):

sudo ./configure --with-systemd

Выпадает ошибка:

checking for gcc... no
checking for cc... no
configure: error: in `/usr/src/postgresql-9.6.5":
configure: error: no acceptable C compiler found in $PATH
See `config.log" for more details

Не найден gcc, установим его:

sudo apt-get install gcc

Следующая ошибка при повторной конфигурации:

checking for library containing readline... no
configure: error: readline library not found
If you have readline already installed, see config.log for details on the
failure.  It is possible the compiler isn"t looking in the proper directory.
Use --without-readline to disable readline support.

Ставим недостающую библиотеку:

sudo apt-get install libreadline-dev

Для redhat подобных систем:

sudo yum install readline-devel

Следующая ошибка библиотека zlib

checking for inflate in -lz... no
configure: error: zlib library not found
If you have zlib already installed, see config.log for details on the
failure.  It is possible the compiler isn"t looking in the proper directory.
Use --without-zlib to disable zlib support.

Ставим и ее:

sudo apt-get install zlibc zlib1g-dev

Для redhat подобных систем:

sudo yum install zlib-devel

Далее ошибка библиотеки libsystemd, ставим ее

sudo apt-get install libsystemd-dev

Для redhat подобных систем:

sudo yum install systemd-devel

Запускаем скрипт configure еще раз и получаем успешный результат.

Устанавливаем пакет make:

sudo apt-get install make

Теперь выполним сборку postgresql:

sudo make

После успешной сборки установим собранный пакет:

sudo make install

Проверякм структуры директорий Postgresql:

ls -l /usr/local/pgsql

total 16
drwxr-xr-x 2 root root 4096 Nov  9 07:33 bin
drwxr-xr-x 6 root root 4096 Nov  9 07:33 include
drwxr-xr-x 4 root root 4096 Nov  9 07:33 lib
drwxr-xr-x 6 root root 4096 Nov  9 07:33 share

Создаем пользователя postgres

sudo useradd -M postgres

Создаем директори для хранения данных:

mkdir -p /var/lib/pgsql/data

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

sudo chown -R postgres:postgres /var/lib/pgsql

Инициализация postgresql

Получаем права пользователя postgres:

su postgres

Запускаем инициализацию:

/usr/local/pgsql/bin/initdb -D /var/lib/pgsql/data/

The files belonging to this database system will be owned by user "postgres".
This user must also own the server process.

The database cluster will be initialized with locale "en_US.UTF-8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".

Data page checksums are disabled.

fixing permissions on existing directory /var/lib/pgsql/data ... ok
creating subdirectories ... ok
selecting default max_connections ... 100
selecting default shared_buffers ... 128MB
selecting dynamic shared memory implementation ... posix
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok

WARNING: enabling "trust" authentication for local connections
You can change this by editing pg_hba.conf or using the option -A, or
--auth-local and --auth-host, the next time you run initdb.

Success. You can now start the database server using:

    /usr/local/pgsql/bin/pg_ctl -D /var/lib/pgsql/data/ -l logfile start

Запускаем демона psotgresql:

/usr/local/pgsql/bin/pg_ctl -D /var/lib/pgsql/data/ -l logfile start

Проверяем подключение к СУБД:

/usr/local/pgsql/bin/psql

psql (9.6.5)
Type "help" for help.

postgres=# 

Для удобства запуска сервиса создадим systemd скрипт для демона Postgresql

sudo touch /etc/systemd/system/postgresql.service

И наполним его следующим содержанием:

cat /etc/systemd/system/postgresql.service

[Unit]
Description=PostgreSQL database server
After=network.target

[Service]
Type=forking

User=postgres
Group=postgres

# Maximum number of seconds pg_ctl will wait for postgres to start.  Note that
# PGSTARTTIMEOUT should be less than TimeoutSec value.
Environment=PGSTARTTIMEOUT=270

Environment=PGDATA=/var/lib/pgsql/data


ExecStart=/usr/local/pgsql/bin/pg_ctl start -D ${PGDATA} -s -w -t ${PGSTARTTIMEOUT}
ExecStop=/usr/local/pgsql/bin/pg_ctl stop -D ${PGDATA} -s -m fast
ExecReload=/usr/local/pgsql/bin/pg_ctl reload -D ${PGDATA} -s

# Give a reasonable amount of time for the server to start up/shut down.
# Ideally, the timeout for starting PostgreSQL server should be handled more
# nicely by pg_ctl in ExecStart, so keep its timeout smaller than this value.
TimeoutSec=300

[Install]
WantedBy=multi-user.target

Останавливаем ранее запущенного демона postgresql:

su postgres -c "/usr/local/pgsql/bin/pg_ctl -D /var/lib/pgsql/data/ stop"

Перезапустим конфигурацию демона systemd:

systemctl daemon-reload

Запустим и добавим в загрузку демона Postgresql:

systemctl start postgresql

systemctl enable postgresql

Основной файл настроек Postgresql это postgresql.conf, который хранится в директории с данными в нашем случае это /var/lib/pgsql/data, там очень много настроек, которые можно посмотреть на официальном сайте в документации, поэтому не будем их рассматривать.

Рассмотрим некоторые варианты настройки доступа к базам данных. Настройки доступа хранятся в файле pg_hba.conf. Они представляют собой строки с указанием типа подключения, база данных к которой разрешено подключение, пользователь который подключается, адрес откуда происходит подключение и метод аутентификации пользователя.

cat /var/lib/pgsql/data/pg_hba.conf

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust
# IPv6 local connections:
host    all             all             ::1/128                 trust
# Allow replication connections from localhost, by a user with the

Рассмотрим возможные значения столбцов:

    Тип подключения:
  • local - подключение через доменные сокеты Unix;
  • host - подключение по TCP/IP;
  • hostssl - подключение по TCP/IP с применением шифрования SSL;
  • hostnossl - противоположен hostssl, подключение по TCP/IP без шифрования SSL.
    Базза данных - определяет к какой базе осуществляется подключение:
  • Имя конкретной баззы данных;
  • all - все баззы данных;
  • sameuser - определяет, что данная запись соответствует только, если имя запрашиваемой базы данных совпадает с именем запрашиваемого пользователя.
  • samerole - определяет, что запрашиваемый пользователь должен быть членом роли с таким же именем, как и у запрашиваемой базы данных.
    Пользователь - учетная запись под которой происходит подключение к базе:
  • Конкретное имя пользователя (несколько пользователей через запятую);
  • all - любой пользователь;
  • знак + перед именем пользователя - подключаемый пользователь имеет отношение к указанной роли;
  • знак @ далее идет имя файла содержащего список пользователей.
    Адрес - адрес клиента, с которого происходит подключение:
  • ip-адрес/маска (172.20.1.0/24, 172.20.1.1/32);
  • all - любой хост;
  • samehost - любой адрес данного сервера;
  • samenet - любой адрес любой сети, к которой сервер подключен напрямую.
    Метод аутентификации:
  • trust - разрешает безусловное подключение;
  • reject - отклоняет подключение;
  • md5 - требует от клиента предоставить пароль;
  • password - требуется для аутентификации клиентом с вводом незашифрованного пароля;
  • ident - получает имя пользователя операционной системы клиента, связываясь с сервером Ident, и проверяет, соответствует ли оно имени пользователя базы данных. Аутентификация ident может использоваться только для подключений по TCP/IP;
  • peer - получает имя пользователя операционной системы клиента из операционной системы и проверяет, соответствует ли оно имени пользователя запрашиваемой базы данных. Доступно только для локальных подключений;
  • ldap - аутентификация с помощью сервера LDAP;
  • radius - аутентификация с помощью сервера Radius;
  • cert - аутентификация с помощью сертификата;
  • pam - аутентификация с помощью службы подключаемых модулей аутентификации (PAM).






Введите ответ:

+

=



Alexey

2019-04-25 07:24:23

Ну при локальном подключении из под самого пользователя postgres при настройке local, пароль ему и не нужен, так как ты уже авторизован в системе.А если по сети тогда нужен пользователь в самой СУБД и конечно же с паролем.


Men

2019-04-23 15:33:35

а пароль для юзера postgres?