- Linux: Iptables Allow PostgreSQL server incoming request
- Open port 5432
- postgresql not accepting tcp/ip on port 5432 for rails on linux
- 1 Answer 1
- Не удается подключиться к postgresql через порт 5432
- Шаг 1: Запуск pg_lsclusters покажет все кластеры postgres, работающие на вашем устройстве
- Шаг 2: перезапустите pg_ctlcluster
- Шаг 3: Шаг 2 не удался и выдал ошибку
- Шаг 4: проверьте право собственности на postgres
- Шаг 5: Проверьте, что пользователь postgres принадлежит к группе пользователей ssl-cert
- Can’t connect to Postgresql on port 5432
- 8 Answers 8
Linux: Iptables Allow PostgreSQL server incoming request
PostgreSQL is an object relational database system that has the features of traditional commercial database systems with enhancements to be found in next-generation DBMS systems. PostgreSQL is free and the complete source code is available.
Open port 5432
By default PostgreSQLt listen on TCP port 5432. Use the following iptables rules allows incoming client request (open port 5432) for server IP address 202.54.1.20 :
As posted earlier, you do not wish give access to everyone. For example in web hosting company or in your own development center, you need to gives access to POSTGRES database server from web server only. Following example allows POSTGRES database server access (202.54.1.20) from Apache web server (202.54.1.50) only:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Allow outgoing POSTGRES client request (made via postgresql command line client or perl/php script), from firewall host 202.54.1.20:
Источник
postgresql not accepting tcp/ip on port 5432 for rails on linux
I’ve tried installing psql on linux but ran into some issues. I downloaded from yaourt and the psql command is running without any issues. It all seems to work fine until I try to run rails db:setup , at which point I’m thrown the error:
This is despite the psql command running okay and the following response from systemctl status postgresql.service
I’ve already tried changing my pg_hba.config to
and changed local addresses to * with listen_addresses = ‘*’ and uncommenting port = 5432 in postgresql.conf.
These files were from /var/lib/postgres/data , which I thought was odd because which psql returns /usr/bin/psql but systemctl confirms that I edited the right ones because the logs mention 0.0.0.0/0
I downloaded postgres with yaourt on antergos, which is an arch based linux distro. PG is added to my gemfile on version 0.18.4 and postgres is installed as version 10.1.
My heroku server which runs the app I’m trying to run db:setup on in production works fine without any issues and the app has also been fine running on a previous install of linux (Ubuntu) on the same laptop and on a mac, suggesting that the issue probably isn’t with this specific rails app. Regardless, here’s the default and dev part of my database.yml file:
And yes, I have made a revisionhubadmin psql account. Running \du in psql gives:
So yeah, I’m a little bit confused. Does anyone know how to fix this?
1 Answer 1
A few steps — first, on the database server, make sure that the socket is open and listening. Something like ss or netstat will help with that:
If it’s confirmed as listening, as I suspect it is as psql works for you and as this log clearly shows:
Does it work from the rails system to the database itself, or are they hosted on the same system? A note, if it’s on the same system, psql will use UNIX domain sockets instead of the actual networked loopback device, so there is a marked difference in how the two communicate wherein the first example will strictly use the file-socket and the second will use the loopback device:
If the second one fails, you genuinely have network connectivity issues, and you’d have to look at firewall rules, connectivity, etc.
If they’re on different systems, and psql runs fine from the rails client host to the database host but we still can’t do migrations, my only other thought is that you could test connectivity to the socket with telnet or some other simple socket tool to see if it really works:
EDIT: I noticed from your configuration that the database is local — I bet that psql in this case worked using the UNIX socket, not the network socket like your rails command is trying to do. Verify the socket is listening and can be connected to with network clients please.
Источник
Не удается подключиться к postgresql через порт 5432
Я установил стек Bitnami Django, который включал PostgreSQL 8.4.
При запуске psql -U postgres я получаю следующую ошибку:
PG определенно работает, и pg_hba.conf файл выглядит так:
«Доказательство», что pg работает:
Эта проблема возникает из-за установки postgres пакета без номера версии. Хотя postgres будет установлен и будет правильной версии, скрипт для настройки кластера не будет работать правильно; это проблема упаковки.
Если вам удобно, postgres есть скрипт, который вы можете запустить, чтобы создать этот кластер и postgres запустить его. Тем не менее, есть более простой способ.
Сначала удалите старую установку postgres. В настоящее время проблема заключается в 9.1, поэтому я буду считать, что это то, что вы установили
Теперь просто переустановите
Запишите название пакета с номером версии. НТН.
Сообщение об ошибке относится к сокету Unix-домена, поэтому вам нужно настроить netstat вызов, чтобы не исключать их. Так что попробуйте без опции -t :
Я предполагаю, что сервер на самом деле слушает сокет, /tmp/.s.PGSQL.5432 а не тот /var/run/postgresql/.s.PGSQL.5432 , к которому ваш клиент пытается подключиться. Это типичная проблема при использовании скомпилированных вручную или сторонних пакетов PostgreSQL в Debian или Ubuntu, потому что исходным по умолчанию для каталога сокетов Unix-домена является, /tmp но пакет Debian меняет его на /var/run/postgresql .
Возможные обходные пути:
- Используйте клиентов, предоставленных вашим сторонним пакетом (звонок /opt/djangostack-1.3-0/postgresql/bin/psql ). Возможно, удалите все пакеты, поставляемые с Ubuntu (это может быть сложно из-за других обратных зависимостей).
- Исправьте каталог сокетов стороннего пакета, чтобы он был совместим с Debian / Ubuntu.
- -H localhost Вместо этого используйте для подключения через TCP / IP.
- Используйте -h /tmp или эквивалентную PGHOST настройку, чтобы указать на правильный каталог.
- Не используйте сторонние пакеты.
Это работает для меня:
Включить или добавить:
Перезапустите ядро базы данных:
Также вы можете проверить файл pg_hba.conf
И добавьте адрес своей сети или хоста:
Вы можете использовать, psql -U postgres -h localhost чтобы заставить соединение происходить по TCP вместо доменных сокетов UNIX; ваш netstat вывод показывает, что сервер PostgreSQL прослушивает порт 5432 локального хоста.
Вы можете узнать, какой локальный сокет UNIX используется сервером PostgrSQL, используя другой вызов netstat :
В любом случае, интерфейсы, на которых слушает сервер PostgreSQL, настроены в postgresql.conf .
Просто создайте мягкую ссылку, подобную этой:
Я заставляю это работать этим:
Выберите предпочитаемые локали и запустите
(9.5 — это моя версия postgresql)
и тогда это работает!
Мне пришлось скомпилировать PostgreSQL 8.1 на Debian Squeeze, потому что я использую Project Open, который основан на OpenACS и не будет работать на более поздних версиях PostgreSQL.
Конфигурация компиляции по умолчанию помещает unix_socket в систему /tmp , но проект Open, который основывается на PostgreSQL, не будет работать , так как это выглядит для unix_socket на /var/run/postgresql .
Есть настройка, postgresql.conf чтобы установить местоположение сокета. Моя проблема заключалась в том, что либо я мог установить /tmp и psql работать, но не открыть проект, либо я мог установить его /var/run/postgresql и psql не работать, но открытие проекта сделало.
Одно из решений этой проблемы состоит в том, чтобы установить сокет для /var/run/postgresql и затем запустить psql , основываясь на предложении Питера, как:
Это выполняется локально с использованием локальных разрешений. Единственным недостатком является то, что он больше печатает, чем просто «psql».
Другое предложение, которое сделал кто-то, состояло в том, чтобы создать символическую связь между этими двумя местоположениями. Это также сработало, но ссылка исчезла после перезагрузки. Возможно, проще использовать аргумент -h, однако я создал символическую ссылку из скрипта PostgreSQL /etc/init.d . Я разместил символическую команду создания ссылки в разделе «Пуск». Конечно, когда я запускаю команду остановки и запуска или перезапуска, она будет пытаться воссоздать существующую символическую ссылку, но, кроме предупреждающего сообщения, в этом нет никакого вреда.
В моем случае вместо:
и явно установить unix_socket /var/run/postgresql/.s.PGSQL.5432 в postgresql.conf .
Решение:
и это. ( 9.3 — это моя текущая версия PostgreSQL. Напишите свою версию!)
Если ваша служба Postgres запущена и работает без каких-либо ошибок или при запуске службы Postgres нет ошибок, но вы все еще получаете указанную ошибку, выполните следующие действия.
Шаг 1: Запуск pg_lsclusters покажет все кластеры postgres, работающие на вашем устройстве
Скорее всего, статус будет ниже в вашем случае и сервис Postgres
Шаг 2: перезапустите pg_ctlcluster
Шаг 3: Шаг 2 не удался и выдал ошибку
Если этот процесс не будет успешным, он выдаст ошибку. Вы можете увидеть журнал ошибок на /var/log/postgresql/postgresql-9.6-main.log
Моя ошибка была:
Шаг 4: проверьте право собственности на postgres
Убедитесь, что postgres это владелец /var/lib/postgresql/version_no/main
Если нет, запустите
Шаг 5: Проверьте, что пользователь postgres принадлежит к группе пользователей ssl-cert
Оказалось, что я ошибочно удалил пользователя Postgres из ssl-cert группы. Запустите приведенный ниже код, чтобы исправить проблему группы пользователей и исправить разрешения
В моем случае это было вызвано опечаткой, которую я сделал при редактировании /etc/postgresql/9.5/main/pg_hba.conf
Но MD5 должен был быть в нижнем регистре md5 :
Я обнаружил, что удаление Postgres звучит неубедительно. Это помогает решить мою проблему:
Запустите сервер postgres:
Убедитесь, что сервер запускается при загрузке:
Подробную информацию можно найти на сайте DigitalOcean здесь.
Я не смог решить эту проблему с моим сервером postgres-9.5. После 3 дней нулевого прогресса, пробуя каждую перестановку исправлений на этом и других сайтах, я решил переустановить сервер и потерять 5 дней работы. Но я повторил проблему на новом экземпляре. Это может дать некоторое представление о том, как это исправить, прежде чем использовать катастрофический подход, который я сделал.
Во-первых, отключите все параметры ведения журнала в postgresql.conf. Это раздел:
Закомментируйте все в этом разделе. Затем перезапустите сервис.
При перезапуске используйте /etc/init.d/postgresql start или restart я нашел полезным находиться в режиме суперпользователя при перезапуске. У меня было открыто окно x только для этой операции. Вы можете установить этот режим суперпользователя с помощью sudo -i .
Убедитесь, что к серверу можно подключиться с помощью этой простой команды: psql -l -U postgres
Если это не помогает, то подумайте:
Я менял владельца многих папок, пытаясь найти решение. Я знал, что я, вероятно, буду пытаться вернуть владельцам этих папок еще chmod два дня. Если вы уже перепутали владельцев этих папок и не хотите полностью очищать свой сервер, начните отслеживать настройки всех затронутых папок, чтобы вернуть их в исходное состояние. Возможно, вы захотите попробовать выполнить параллельную установку в другой системе и систематически проверять владение и настройки всех папок. Утомительно, но вы можете получить доступ к своим данным.
Источник
Can’t connect to Postgresql on port 5432
I have PostgreSQL 9.3 installed on a server running Ubuntu Server 14.04.
If I ssh into the server via terminal, I’m able to connect with psql. But when I try to configure pgAdmin III to do the remote connection, I get:
Server doesn’t listen The server doesn’t accept connections: the connection library reports could not connect to server: Connection refused Is the server running on host «172.24.3.147» and accepting TCP/IP connections on port 5432?
When I run on the server service postgresql status it gives me:
So of course I’m missing something important here.
When running netstat -na on the server, I get (relevant portion, I guess):
8 Answers 8
You have to edit postgresql.conf file and change line with ‘listen_addresses’.
This file you can find in the /etc/postgresql/9.3/main directory.
Default Ubuntu config have allowed only localhost (or 127.0.0.1) interface, which is sufficient for using, when every PostgreSQL client work on the same computer, as PostgreSQL server. If you want connect PostgreSQL server from other computers, you have change this config line in this way:
Then you have edit pg_hba.conf file, too. In this file you have set, from which computers you can connect to this server and what method of authentication you can use. Usually you will need similar line:
Please, read comments in this file.
After the editing postgresql.conf and pg_hba.conf you have to restart postgresql server.
EDIT2: Highlited configuration files.
Uncomment the listen_addresses = ‘*’ in the postgresql.conf
This has bitten me a second time so I thought might be worth mentioning. The line listen_addresses = ‘*’ in the postgresql.conf is by default commented. Be sure to uncomment (remove the pound sign, # at the beginning) it after updating otherwise, remote connections will continue to be blocked.
PS: psql -U postgres -c ‘SHOW config_file’ — to locate the postgresql.conf file path
Had same problem with psql via command line connecting and pgAdmin not connecting on RDS with AWS. I did have my RDS set to Publicly Accessible. I made sure my ACL and security groups were wide open and still problem so, I did the following: sudo find . -name *.conf then sudo nano ./data/pg_hba.conf then added to top of directives in pg_hba.conf file host all all 0.0.0.0/0 md5 and pgAdmin automatically logged me in.
This also worked in pg_hba.conf file host all all md5 without any IP address and this also worked with my IP address host all all /32 md5
As a side note, my RDS was in my default VPC. I had an identical RDS instance in my non-default VPC with identical security group, ACL and security group settings to my default VPC and I could not get it to work. Not sure why but, that’s for another day.
Remember to check firewall settings as well. after checking and double-checking my pg_hba.conf and postgres.conf files I finally found out that my firewall was overriding everything and therefore blocking connections
You probably need to either open up the port to access it in your LAN (or outside of it) or bind the network address to the port (make PostgreSQL listen on your LAN instead of just on localhost)
I had the same problem after a MacOS system upgrade. Solved it by upgrading the postgres with brew. Details: it looks like the system was trying to access Postgres 11 using older Postgres 10 settings. I’m sure it was my mistake somewhere in the past, but luckily it all got sorted out with the upgrade above.
I had this same issue. I originally installed version 10 because that was the default install with Ubuntu 18.04. I later upgraded to 13.2 because I wanted the latest version. I made all the config modifications, but it was still just binging to 1207.0.0.1 and then I thought — maybe it is looking at the config files for version 10. I modified those and restarted the postgres service. Bingo! It was binding to 0.0.0.0
I will need to completely remove 10 and ensure that I am forcing the service to run under version 13.2, so if you upgraded from another version, try updating the other config files in that older directory.
Источник