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.
psql command not found |
|
ERROR: character with byte sequence 0xd0 0x9a in encoding «UTF8» has no equivalent in encoding «WIN1252» |
|
ERROR: database «db» is being accessed by other users |
|
FATAL password authentication failed for user postgres |
|
ERROR: could not open file «/home/user…» for reading: Permission denied |
|
ERROR: COPY quote must be a single one-byte character |
|
ERROR: date/time field value out of range |
|
Job for postgresql.service failed because the control process exited with error code |
|
psql: could not connect to server: No such file or directory |
|
pg_basebackup: could not connect to server: No route to host |
|
Failed to stop postgresql.service: Unit postgresql.service not loaded |
|
ERROR: WAL level not sufficient for making an online backup |
|
NOTICE: WAL archiving is not enabled |
Ошибки
psql command not found
Вы хотите запустить Postgres скрипт из bash
andrey@olegovich-10:/mnt/c/Users/olegovich$ psql -h localhost -p 5432 -U andrei
но получаете эту ошибку
-bash: psql: command not found
Это значит, что путь до Postgres не прописан в $PATH
Чтобы узнать, что прописано в $PATH достаточно сделать
echo $PATH
/home/andrei/bin:/home/andrei/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/mnt/c/Program Files (x86)/Common Files/Oracle/Java/javapath_target_1128437:/mnt/c/ProgramData/Oracle/Java/javapath_target_5252250:/mnt/c/Windows/System32:/mnt/c/Windows:/mnt/c/Windows/System32/wbem:/mnt/c/Windows/System32/WindowsPowerShell/v1.0:/mnt/c/Program Files/OpenVPN/bin:/mnt/c/Program Files (x86)/Microsoft SQL Server/Client SDK/ODBC/130/Tools/Binn:/mnt/c/Program Files (x86)/Microsoft SQL Server/140/Tools/Binn:/mnt/c/Program Files (x86)/Microsoft SQL Server/140/DTS/Binn:/mnt/c/Program Files (x86)/Microsoft SQL Server/140/Tools/Binn/ManagementStudio:/mnt/c/Program Files/MiKTeX 2.9/miktex/bin/x64:/mnt/c/Users/andreyolegovich_ru/Documents/Software/axis2-1.6.2:/mnt/c/Users/andreyolegovich_ru/Documents/Software/axis2-1.6.2/bin:/mnt/c/Windows/System32/OpenSSH:/mnt/c/Program Files/TortoiseSVN/bin:/mnt/c/Program Files/Microsoft SQL Server/Client SDK/ODBC/130/Tools/Binn:/mnt/c/Program Files/Microsoft SQL Server/140/Tools/Binn:/mnt/c/Program Files/Microsoft SQL Server/140/DTS/Binn:/mnt/c/Program Files (x86)/Intel/Intel(R) Management Engine Components/DAL:/mnt/c/Program Files/Intel/Intel(R) Management Engine Components/DAL:/mnt/c/Program Files/TortoiseGit/bin:/mnt/c/Program Files/Git/cmd:/mnt/c/Program Files/nodejs:/mnt/c/Program Files/Intel/WiFi/bin:/mnt/c/Program Files/Common Files/Intel/WirelessCommon:/mnt/c/Program Files/PuTTY:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Continuum/anaconda3:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Continuum/anaconda3/Library/mingw-w64/bin:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Continuum/anaconda3/Library/bin:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Continuum/anaconda3/Scripts:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Programs/Python/Python36/Scripts:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Programs/Python/Python36:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Microsoft/WindowsApps:/mnt/c/Users/andreyolegovich_ru/AppData/Local/atom/bin:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Programs/Python/Python36-32:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Programs/Python/Python36-32/Scripts:/mnt/c/Program Files (x86)/Nmap:/mnt/c/Program Files (x86)/Mozilla Firefox:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Microsoft/WindowsApps:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Programs/Fiddler:/mnt/c/Program Files/JetBrains/PyCharm Community Edition 2018.3.2/bin:/mnt/c/Users/andreyolegovich_ru/AppData/Roaming/npm:/mnt/c/Program Files/Intel/WiFi/bin:/mnt/c/Program Files/Common Files/Intel/WirelessCommon:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Programs/Microsoft VS Code/bin:/snap/bin
ERROR: character with byte sequence 0xd0 0x9a in encoding «UTF8»
has no equivalent in encoding «WIN1252»
Скорее всего Вы создали базу данных, и даже смогли туда что-то импортировать, например, из .csv файла.
Но сделать SELECT * FROM table; уже не получается, потому что кодировка базы и кодировка файла не совпадают.
Возможно, Вы уже попробовали явно указать SET CLIENT_ENCODING TO ‘utf8’; при импорте файла. Но так как кодировка WIN1252
— это кодировка БД, способ не сработал.
Нужно привести файл и БД к одной кодировке — пересоздайте БД в utf8, например.
Как проверить кодировки я писал выше —
Проверка кодировок БД
Как указать кодировку при создании БД —
Создание БД
ERROR: database «db» is being accessed by other users
Если Вы делаете DROP DATABASE db; и получаете
ERROR: database «db» is being accessed by other users
DETAIL: There are 2 other sessions using the database.
Значит где-то ещё не закрыто подключение к БД. Например, Вы открывали её через pgAdmin.
Нужно найти это подключение и закрыть
FATAL password authentication failed for user postgres
Если вы логинитесь в pgAdmin, но не помните пароль — его можно поменять через терминал
sudo su — postgres
psql
postgres=# ALTER USER postgres PASSWORD ‘новый_пароль’;
ALTER ROLE
ERROR: could not open file «/home/user…» for reading: Permission denied
Если вы пытаетесь прочитать из файла, а получаете
ERROR: could not open file «/home/user/file.csv» for reading: Permission denied
HINT: COPY FROM instructs the PostgreSQL server process to read a file. You may want a client-side facility such as psql’s copy. SQL state: 42501
Значит у postgres недостаточно прав для чтения из файла. Простое добавление прав на чтение вроде
chmod +r file.csv
Проблему, скорее всего, не решит.
Как вариант — предлагаю переместить нужный файл в директорию /tmp
cp /home/user/file.csv /tmp
ERROR: COPY quote must be a single one-byte character
Если вы пытаетесь прочитать из файла, а получаете
ERROR: COPY quote must be a single one-byte character
SQL state: 0A000
Скорее всего присутствует какой-то лишний символ в QUOTE, например
QUOTE ‘»‘
Замените на
QUOTE ‘»‘
ERROR: date/time field value out of range
Если вы пытаетесь прочитать из .csv файла, а получаете
ERROR: date/time field value out of range: «» HINT: Perhaps you need a different «datestyle» setting. CONTEXT: «» SQL state: 22008
Скорее всего ваш текущий datestyle не совпадает с тем, который используется в .csv файле.
datestyle — это порядок записи даты. Может быть День — Месяц — Год (DDMMYYYY), Год — Месяц — День (YYYYMMDD) или,
например американский стиль Месяц — День — Год (MMDDYYYY)
Это всё актуально если тип столбца указан как дата date. Можно изменить тип на char тогда datestyle уже не нужно настраивать.
Стилей много и если они не совпадают — получается что месяц принимает значение больше 12.
Как вариант — можно перед выполнение скрипта временно изменить свой datestyle.
Например, если нужно импортировать данные из .csv с американским стилем — перед импортом добавьте
set datestyle to «US»;
psql: could not connect to server: No such file or directory
Если вы выполнили
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»?
Очень часто данная ошибка возникает вследствии того, что не была инициализирована база
данных.
Выполните
postgresql-setup initdb
Initializing database … OK
pg_basebackup: could not connect to server: could not connect to server: No route to host
Если вы пытаетесь сделать реплику
pg_basebackup -h 192.168.56.109 -U repluser -D /var/lib/pgsql/data —xlog-method=stream
pg_basebackup: could not connect to server: could not connect to server: No route to host
Is the server running on host «192.168.56.109» and accepting
TCP/IP connections on port 5432?
На мастере
sudo firewall-cmd —zone=public —add-port=5432/tcp —permanent
success
sudo firewall-cmd —reload
success
sudo firewall-cmd —list-ports
3389/tcp 5432/tcp
Failed to stop postgresql.service: Unit postgresql.service not loaded
Причин может быть много но среди новичков самая распространённая — попытка остановить postgresql
из под пользователя postges
Например, в моём терминале я по приглашению bash-4.2$ вижу, что зашёл как postgres
Нужно выполнить
exit
Приглашение изменится на
[andrei@localhost ~]$
И затем уже можно останавливать сервер
sudo systemctl stop postgresql
sudo systemctl status postgresql
● postgresql.service — PostgreSQL database server
Loaded: loaded (/usr/lib/systemd/system/postgresql.service; disabled; vendor preset: disabled)
Active: inactive (dead)
Jun 09 12:20:24 localhost.localdomain systemd[1]: Unit postgresql.service entered failed state.
Jun 09 12:20:24 localhost.localdomain systemd[1]: postgresql.service failed.
Jun 09 12:21:59 localhost.localdomain systemd[1]: Starting PostgreSQL database server…
Jun 09 12:22:00 localhost.localdomain systemd[1]: Started PostgreSQL database server.
Jun 10 19:10:02 localhost.localdomain systemd[1]: Stopping PostgreSQL database server…
Jun 10 19:10:03 localhost.localdomain systemd[1]: Stopped PostgreSQL database server.
Jun 10 22:14:18 localhost.localdomain systemd[1]: Starting PostgreSQL database server…
Jun 10 22:14:19 localhost.localdomain systemd[1]: Started PostgreSQL database server.
Jun 11 10:11:15 localhost.localdomain systemd[1]: Stopping PostgreSQL database server…
Jun 11 10:11:16 localhost.localdomain systemd[1]: Stopped PostgreSQL database server.
ERROR: WAL level not sufficient for making an online backup
Вы хотите настроить онлайн бэкап, например с помощью команды
-bash-4.2$ psql -c «SELECT pg_start_backup(‘replbackup’);»
Но получаете ошибку
ERROR: WAL level not sufficient for making an online backup
HINT: wal_level must be set to «archive» or «hot_standby» at server start.
Нужно узнать расположение конфигурационного файла
postgresql.conf
-bash-4.2$ su — postgres -c «psql -c ‘SHOW config_file;'»
Password:
config_file
————————————-
/var/lib/pgsql/data/postgresql.conf
(1 row)
vi /var/lib/pgsql/data/postgresql.conf
Нужно установить wal_level = hot_standby
NOTICE: WAL archiving is not enabled
Вы заканчиваете бэкап, например с помощью команды
psql -c «SELECT pg_stop_backup();»
Но получаете предупреждение
NOTICE: WAL archiving is not enabled; you must ensure that all required WAL segments are copied through other means to complete the backup
Contents
- Introduction
- Client Installation
-
Installation
- Installing PostGIS, procedural languages, client interfaces, etc
- Administration
-
Basic Server Setup
- Create database
- Install Server Instrumentation (for PgAdmin) for Postgresql 8.4 or 9.3
- Alternative Server Setup
- Using pgAdmin III GUI
-
Managing the Server
- Managing users and rights
- restarting the server
- Further reading
-
Troubleshooting
- fe_sendauth: no password supplied
- FATAL: role «myusername» does not exist
- FATAL: database «myusername» does not exist
- FATAL: Peer authentication failed for user «myusername»
- could not connect to server: No such file or directory
-
External Links
- Official PostgreSQL downloads
- EnterpriseDB
- Turnkey Linux
Introduction
PostgreSQL is a powerful object-relational database management system, provided under a flexible BSD-style license.[1] PostgreSQL contains many advanced features, is very fast and standards compliant.
PostgreSQL has bindings for many programming languages such as C, C++, Python, Java, PHP, Ruby… It can be used to power anything from simple web applications to massive databases with millions of records.
Client Installation
If you only wish to connect to an external PostgreSQL server, do not install the main PostgreSQL package, but install the PostgreSQL client package instead. To do this, use the following command
sudo apt-get install postgresql-client
you then connect to the server with the following command
psql -h server.domain.org database user
After you inserted the password you access PostgreSQL with line commands. You may for instance insert the following
SELECT * FROM table WHERE 1;
You exit the connection with
q
Installation
To install the server locally use the command line and type:
sudo apt-get install postgresql postgresql-contrib
This will install the latest version available in your Ubuntu release and the commonly used add-ons for it.
See «External Links» below for options for getting newer releases.
Installing PostGIS, procedural languages, client interfaces, etc
Additional packages contain procedural language runtimes, add-ons like PostGIS, language client interfaces like psycopg2 for Python, etc. You can get a listing with:
apt-cache search postgres
Administration
pgAdmin III is a handy GUI for PostgreSQL, it is essential to beginners. To install it, type at the command line:
sudo apt-get install pgadmin3
You may also use the Synaptic package manager from the System>Administration menu to install these packages.
Basic Server Setup
To start off, we need to set the password of the PostgreSQL user (role) called «postgres»; we will not be able to access the server externally otherwise. As the local “postgres” Linux user, we are allowed to connect and manipulate the server using the psql command.
In a terminal, type:
sudo -u postgres psql postgres
this connects as a role with same name as the local user, i.e. «postgres», to the database called «postgres» (1st argument to psql).
Set a password for the «postgres» database role using the command:
password postgres
and give your password when prompted. The password text will be hidden from the console for security purposes.
Type Control+D or q to exit the posgreSQL prompt.
Create database
To create the first database, which we will call «mydb», simply type:
sudo -u postgres createdb mydb
Install Server Instrumentation (for PgAdmin) for Postgresql 8.4 or 9.3
PgAdmin requires the installation of an add-on for full functionality. The «adminpack» addon, which it calls Server Instrumentation, is part of postgresql-contrib, so you must install that package if you haven’t already:
sudo apt-get install postgresql-contrib
Then to activate the extension, for «»Postgresql 8.4″», run the adminpack.sql script, simply type:
sudo -u postgres psql < /usr/share/postgresql/8.4/contrib/adminpack.sql
For «Postgresql 9.3″+ install the adminpack «extension» in the «postgres» database:
sudo -u postgres psql CREATE EXTENSION adminpack;
Alternative Server Setup
If you don’t intend to connect to the database from other machines, this alternative setup may be simpler.
By default in Ubuntu, Postgresql is configured to use ‘ident sameuser’ authentication for any connections from the same machine. Check out the excellent Postgresql documentation for more information, but essentially this means that if your Ubuntu username is ‘foo’ and you add ‘foo’ as a Postgresql user then you can connect to the database without requiring a password.
Since the only user who can connect to a fresh install is the postgres user, here is how to create yourself a database account (which is in this case also a database superuser) with the same name as your login name and then create a password for the user:
sudo -u postgres createuser --superuser $USER sudo -u postgres psql
postgres=# password $USER
Client programs, by default, connect to the local host using your Ubuntu login name and expect to find a database with that name too. So to make things REALLY easy, use your new superuser privileges granted above to create a database with the same name as your login name:
sudo -u postgres createdb $USER
Connecting to your own database to try out some SQL should now be as easy as:
psql
Creating additional database is just as easy, so for example, after running this:
create database amarokdb;
You can go right ahead and tell Amarok to use postgresql to store its music catalog. The database name would be amarokdb, the username would be your own login name, and you don’t even need a password thanks to ‘ident sameuser’ so you can leave that blank.
Using pgAdmin III GUI
To get an idea of what PostgreSQL can do, you may start by firing up a graphical client. In a terminal type :
pgadmin3
You will be presented with the pgAdmin III interface. Click on the «Add a connection to a server» button (top left). In the new dialog, enter the address 127.0.0.1 (Local host is default, so it can be left out.), a description of the server, the default database («mydb» in the example above), your username («postgres») and your password. One more step is required in order to allow pgAdmin III to connect to the server, and that is to edit pg_hba.conf file and change the authentication method from peer to md5 (will not work if you have not set the password):
sudo nano /etc/postgresql/9.3/main/pg_hba.conf
and change the line
# Database administrative login by Unix domain socket local all postgres peer
to
# Database administrative login by Unix domain socket local all postgres md5
Now you should reload the server configuration changes and connect pgAdmin III to your PostgreSQL database server.
sudo /etc/init.d/postgresql reload
With this GUI you may start creating and managing databases, query the database, execute SQl etc.
Managing the Server
To learn more about managing PostgreSQL (but without the Ubuntu specifics) see the official PostgreSQL documentation
Managing users and rights
User management is discussed in detail in the client authentication chapter of the PostgreSQL documentation; the following is an introduction to get you started.
To manage users, you first have to edit /etc/postgresql/current/main/pg_hba.conf and modify the default configuration which is very locked down and secure. For example, if you want postgres to manage its own users (not linked with system users), you will add the following line:
8<------------------------------------------- # TYPE DATABASE USER IP-ADDRESS IP-MASK METHOD host all all 10.0.0.0 255.255.255.0 md5 8<-------------------------------------------
Which means that on your local network (10.0.0.0/24 — replace with your own local network !), postgres users can connect through the network to the database providing a classical couple user / password.
Besides allowing a user to connect over the network to the to a database on the server, you must enable PostgreSQL to listen across different networks. To do that, open up /etc/postgresql/current/main/postgresql.conf in your favourite editor and alter the listen_addresses as below:
listen_addresses = '*'
to listen on all network interfaces. See the docs for listen_addresses for other options.
To create a database with a user that have full rights on the database, use the following command:
sudo -u postgres createuser -D -A -P myuser sudo -u postgres createdb -O myuser mydb
The first command line creates the user with no database creation rights (-D) with no add user rights -A) and will prompt you for entering a password (-P). The second command line create the database ‘mydb with ‘myuser‘ as owner.
This little example will probably suit most of your needs. For more details, please refer to the corresponding man pages or the online documentation.
restarting the server
After configuring the networking / users you may need to reload the server, here is a suggested command to do so.
sudo /etc/init.d/postgresql reload
Some settings changes in postgresql.conf require a full restart, which will terminate active connections and abort uncommitted transactions:
sudo /etc/init.d/postgresql restart
Further reading
If you are not familiar with SQL you may want to look into this powerful language, although some simple uses of PostgreSQL may not require this knowledge (such as a simple Django project).
The PostgreSQL website contains a wealth of information on using this database. In particular, the tutorial is a useful starting point, but you can skip the installation step as you’ve already installed it using Ubuntu packages.
Troubleshooting
fe_sendauth: no password supplied
Your pg_hba.conf specifies that md5 authentication is to be used for this connection based on the origin host, connection method and the requested username/database, but your application didn’t supply a password.
Change the authentication mode or set a password for the user you’re connecting to and then specify that password in your application’s connection settings.
FATAL: role «myusername» does not exist
By default PostgreSQL connects to the PostgreSQL user with the same name as the current unix user. You have not created a PostgreSQL user by that name in your database.
Create a suitable user, or specify a different username to connect with. In the command line tools the -U flag does this.
FATAL: database «myusername» does not exist
A user named «myusername» exists, but there’s no database of the same name.
By default PostgreSQL connects to the database with the same name as the user you’re connecting as, but it doesn’t auto-create the database if it doesn’t exist.
Create the database, or specify a different database to connect to.
FATAL: Peer authentication failed for user «myusername»
You are connecting to localhost via a unix socket. A user named «myusername» exists, but your current unix user is not the same as that username. PostgreSQL is set to use «peer» authentication on unix sockets for this user/db combo so it requires your unix and postgresql usernames to match.
Connect from the unix user that matches the desired PostgreSQL user — perhaps with sudo -u theusername psql — or change pg_hba.conf to use a different authentication mode like «md5» for this username.
could not connect to server: No such file or directory
An error like this (possibly with a different unix socket path, depending on your install):
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"?
can mean a number of things:
* The server isn’t running;
* The server has a different unix_socket_directories to the default in your client’s libpq, either due to different compiled-in defaults or a mismatched setting;
* The server is listening on a different «port». PostgreSQL emulates TCP/IP ports on unix sockets by using the port number as the suffix for the socket file, e.g. 5432.
Eliminate these in turn.
First make sure the server is running. On Ubuntu, ps -u postgres -f will show you any processes running as user postgres — you want to see multiple ones named postgres.
Now make sure the server is listening where your client thinks it is. To find out your PostgreSQL server’s socket directory:
sudo -u postgres psql -c "SHOW unix_socket_directories;"
or on older PostgreSQL versions, unix_socket_directory as the parameter changed name. To show the server’s port (which applies for both TCP/IP and unix sockets):
sudo -u postgres psql -c "SHOW port;"
If you can’t even connect with psql under unix user postgres you can check the socket dir with lsof:
$ sudo lsof -U -a -c postgres COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME postgres 6565 postgres 5u unix 0xffff88005a049f80 0t0 183009 /tmp/.s.PGSQL.5432 postgres 6566 postgres 1u unix 0xffff88013bc22d80 0t0 183695 socket postgres 6566 postgres 2u unix 0xffff88013bc22d80 0t0 183695 socket
In this case the first line is the socket location. This server has socket directory /tmp with port 5432.
If your client is looking in a different socket directory, you’re probably trying to connect over unix sockets to the default socket path and/or to the default port, and the libpq your client application is linked to has a different compiled-in unix socket path and/or port than your running PostgreSQL. Most likely your LD_LIBRARY_PATH or /etc/ld.so.conf has a different libpq before the one that came with your version of PostgreSQL. This doesn’t generally matter much, you can just override the socket directory.
To specify an alternative socket directory and/port port to connect to, specify the socket dir as the host parameter in your connection options, e.g. to connect as user bob to the server listening in /tmp on port 5433:
psql -h /tmp -p 5433 -U bob ...
or in connection-string form:
psql "host=/tmp port=5433 user=bob ..."
The same works with any client that uses libpq (all the PostgreSQL client tools, plus e.g. psycopg2, the Pg gem in Ruby/Rails, PHP’s postgres and PDO, Perl’s DBB::Pg, etc). It does NOT work with non-libpq clients like PgJDBC, py-postgresql, etc, but most of these don’t support unix sockets at all. See the client documentation for non-libpq based clients.
[1] You do not have to pay in order to use PostgreSQL for any application, such as commercial closed source software. See http://www.postgresql.org/about/licence/.
External Links
Official PostgreSQL downloads
The PostgreSQL project provides an official list of download locations, including an Ubuntu software repository, at its download page. In particular, Ubuntu users can get newer PostgreSQL versions than those packaged in their Ubuntu release using apt-get via apt.postgresql.org.
For support and services around PostgreSQL see the services and support page.
EnterpriseDB
The PostgreSQL Linux downloads page contains a section on «Graphical installer» built by EnterpriseDB. You download the installer, change its properties to allow to run it as command (it has .run extension), and run it from command prompt as in «sudo whateveritwas.run».
You end up with
- configured DB server instance, which starts with your server
- pgAdmin III UI client application
Note that the installed software will not be integrated with Ubuntu software center. As a result, you will not receive any security updates from Ubuntu. However, the installed version will closely match the latest Ubuntu version.
Turnkey Linux
An Ubuntu-based PostgreSQL appliance is one of the easiest ways to get up and running with PostgreSQL on Ubuntu. It’s part of a family of pre-integrated TurnKey Linux Software Appliances based on Ubuntu 10.04.1 (Lucid LTS).