Не удалось создать файл блокировки postmaster pid permission denied
Hi,
I tried to launch a docker-compose up --build in a server however I get the error :
FATAL: lock file "postmaster.pid" already exists
HINT: Is another postmaster (PID 90) running in data directory "/var/lib/postgresql/13/main"?
I have tried deleting container, image, volumes, I have tried the command docker system prune --volumes but I still get the same error. How is it possible ? I also tried changing volumes to named volumes but id di not changed anything.
My current docker-compose.yml looks like this:
I can't find the postmaster.pid file nor kill the process because the container is directly exiting with code 1. I read loads of forum but can't seem to find what's wrong. If you have any idea, I would be really grateful ! Thanks
The text was updated successfully, but these errors were encountered:
3 Answers 3
The permissions and ownership on /var/lib/pgsql/data should be:
If they are not do as root:
Thanks a lot for replying. But even after changing permission and ownership it is giving me the same error..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"?
The last error from the pglog.log you posted is about permissions. Is it the same now? Did you change pg_hba as the postgres user?
Thanks a lot. Now my problem w.r.t psql is indeed solved. Can you also help me with this. I am now getting the error "FATAL: Ident authentication failed for user "postgres"". Even though I changed ph_hba's method to trust still I am getting the error of authentication failure. Thanks a lot again..hope u will also solve this problem of mine. please please
Check in the pglog.log file to ensure that the server did actually start without error. Given the error it seems like it did not start properly.
It's listing a number of fatal errors regarding permissions so I would check that first as well as ensuring that a separate Postgres process is not already running which the logs also note.
The postmaster.pid file should contain the process ID and then you can check to see if that process is still running.
You probably don't have your server configured to put unix domain sockets in "/tmp". It's probably somewhere like "/var/run/pgsql" but see your postgresql.conf file to see exactly what.
Then you can specify this directory as a "host" on the command-line:
If that's not the problem, check the port number.
Not sure why/how your psql client and postgresql server have different default paths, but then I've never heard of the site you got the instructions from, so I've no idea how useful they are.
После перезапуска моего Mac я получил ужасную ошибку Postgres:
Причина, по которой это произошло, заключается в том, что мой macbook полностью завис из-за несвязанной проблемы, и мне пришлось выполнить жесткую перезагрузку с помощью кнопки питания. После перезагрузки мне не удалось запустить Postgres из-за этой ошибки.
Когда вы оставляете ответ, попробуйте объяснить, ПОЧЕМУ это происходит, или как работает система Postgres, чтобы мы не все просто пробовали случайные вещи.
ВНИМАНИЕ: Если вы удалите postmaster.pid, не убедившись, что на самом деле нет postgres запущенных вами процессов, это может привести к необратимому повреждению вашей базы данных . (PostgreSQL должен удалить его автоматически, если postmaster завершил работу.).
РЕШЕНИЕ: это устранило проблему - я удалил этот файл, и все заработало!
и вот как я понял, почему это нужно было удалить.
Я использовал следующую команду, чтобы увидеть, запущены ли какие-либо процессы PG. для меня их не было, я даже не мог запустить PG сервер:
это ничего не показало после поиска по всему моему компьютеру, поэтому файл не существовал, но, очевидно, psql «хотел» или «думал, что он там».
Я просмотрел журналы своего сервера и увидел следующую ошибку:
в конце журнала сервера я вижу следующую ошибку:
Надеюсь, этот ответ поможет кому-то другому, и спасибо человеку, который его поддержал. несмотря на то, что модератор пометил этот вопрос как дублирующий, он уникален и полезен. спасибо за переполнение стека за отличный сайт и экспертов за то, что поделились!
Просто FWIW, удаление postmaster.pid опасно, вы должны быть действительно уверены, что нет никаких postgres запущенных процессов, прежде чем это делать.
Отличный ответ. Спасибо за публикацию всего процесса, а не только за потенциально деструктивную команду!
Согласовано. Ответ о postmaster.pid хорош, но каждый шаг процесса выяснения того, работает ли / где postgres, бесценен . Спасибо!
У меня ничего из вышеперечисленного не сработало. Мне пришлось переустановить Postgres следующим образом:
Удалите postgresql с помощью brew: brew uninstall postgresql
Удалите все папки Postgres:
rm -r /usr/local/var/postgres
rm -r ~/Library/Application\ Support/Postgres
Переустановите postgresql с помощью brew: brew install postgresql
Стартовый сервер: brew services start postgresql
Теперь вам нужно создать свои базы данных . ( createdb )
Сработало для меня, но мне не нужно было удалять фактическую базу данных, и у меня не было папки в поддержке приложений. Я думаю, дело в том, что некоторые элементы brew сломали символические ссылки при установке postgres. Их исправление и повторная установка postgres решила проблему. Спасибо!
Ни этот, ни главный ответ у меня не сработали, пока я тоже не запустил brew postgresql-upgrade-database
Чтобы подтвердить: это удаляет все ваши базы данных, верно? Я смог обойтись только одним brew reinstall postgres , подтвердив, что последний номер основной версии Homebrew Postgres был таким же, как мой текущий (сломанный).
Если вы используете macOS и установили postgres через homebrew, попробуйте перезапустить его с помощью
Если вы используете Ubuntu, вы можете перезапустить его с помощью любой из этих команд.
Возможно, это не связано, но аналогичная ошибка появляется при обновлении postgres до основной версии с помощью brew ; с помощью brew info postgresql выяснил, что это помогло:
Это сработало для меня, когда не было сделано никаких других остановок и запуска / перезапуска / переустановки Postgres с использованием homebrew. Спасибо @ smartworld-dm
Это душа, к которой я всегда возвращаюсь. Я мог бы добавить псевдоним, который при запуске fix-my-postgresql выполнит это :)
Похоже, но по-другому :) . brew services stop postgresql; rm /usr/local/var/postgres/postmaster.pid; сервисы brew запускают postgresql
Следующие команды выручили меня. Проблема была в версии данных PostgreSQL. После обновления у меня все стало нормально работать.
Удивлен . Я просто устанавливаю postgresql на свою MAC OS, чем при подключении, сбой подключения. postgresql не работает в фоновом режиме, когда я запускаю как службу, но после этих команд. Все работает отлично.
^^^ эта последовательность сработала для меня, рабочее решение для macOS по состоянию на июнь 2021 года. Спасибо за документирование @ satendra-rawat! Если это не сработает, возможно, это устаревший PID, и тогда я бы попробовал решение @ smartworld-dm, указанное выше.
если ваш postmaster.pid ушел, и вы не можете перезапустить или что-то еще, сделайте следующее:
pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start
как объяснено здесь изначально
Другой класс причин, по которым это может произойти, связан с обновлениями версии Postgres.
Вы можете подтвердить, что это проблема, посмотрев журналы postgres:
и видя такие записи:
В этом случае (при условии, что вы находитесь на Mac и используете brew ) просто запустите:
(Как ни странно, он потерпел неудачу в первом прогоне и работал во втором прогоне, поэтому попробуйте дважды, прежде чем сдаваться)
👍🏻 Это сработало для меня, и мне пришлось запустить его дважды - в первый раз он не удался с исходной ошибкой: connection to database failed: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/usr/local/var/log/.s.PGSQL.50432"? но запуск во второй раз сработал ¯ \ _ (ツ) _ / ¯
Привет, мир :)
Лучшим, но странным для меня способом было делать следующее.
1) Загрузите postgres93.app или другую версию. Добавьте это приложение в папку / Applications /.
2) Добавьте строку (команду) в файл .bash_profile (который находится в моем домашнем каталоге):
Это ПУТЬ к psql от Postgres93.app . Строка (команда) запускается каждый раз при запуске консоли.
3) Запускаем Postgres93.app из /Applications/ папки. Он запускает локальный сервер (порт - «5432», а хост - «localhost»).
4) После всех этих манипуляций я был рад запустить $ createuser -SRDP user_name и другие команды и убедиться, что все заработало ! Postgres93.app может запускаться каждый раз при запуске вашей системы.
5) Также, если вы хотите увидеть свои базы данных графически, вам следует установить PG Commander.app . Это хороший способ увидеть вашу базу данных postgres как красивые таблицы данных
Конечно, это полезно только для локального сервера. Буду рад, если эта инструкция поможет другим, кто сталкивался с этой проблемой.
Ключевым моментом здесь является добавление Postgres на ваш путь (шаг 2). Это мне помогло. Если вы установили Postgres с помощью Homebrew, вы можете добавить его в свой путь, добавив следующую строку в свой .bash_profile: export PATH='/usr/local/Cellar/postgresql/9.4.1/bin/':$PATH - Имейте в виду, что номер вашей версии может быть другим.
Для меня решением было просто перезагрузить компьютер. Сначала я попытался перезапустить с помощью сервисов Brew, и когда это не сработало, перезапуск показался мне следующим лучшим вариантом, прежде чем искать некоторые из наиболее сложных решений. После все заработало как надо.
1) Если у вас какой-то сбой, вероятно, потребуется удалить файл /usr/local/var/postgres/postmaster.pid, поскольку postgres, возможно, не справился с этим должным образом. Но убедитесь, что ни один процесс не запущен.
3) Другое решение - удалить и переустановить гем. Также может потребоваться обновление пивоварни.
Если вы наткнетесь на этот пост, если вы сможете определить один из источников, вы сэкономите время .
Я столкнулся с аналогичной проблемой, я решил эту проблему, как показано ниже.
На самом деле процесс postgres мертв, чтобы увидеть статус postgres, выполните следующую команду
Он скажет, что процесс мертв, просто запустите процесс
Спасибо за ответ, ваш ответ помог мне решить ту же проблему с некоторыми изменениями: sudo /etc/init.d/postgresql start
Я столкнулся с той же проблемой для psql (PostgreSQL) 9.6.11 .
что сработало для меня -
удалить postmaster.pid - rm /usr/local/var/[email protected]/postmaster.pid
перезапустить postgres - brew services restart [email protected]
Если postmaster.pid не существует или вышеуказанный процесс не работает, запустите -
sudo chmod 700 /usr/local/var/[email protected]
Это решение помогло мне решить мою обычную проблему с [email protected] . Я часто сталкиваюсь с этой проблемой всякий раз, когда мой ноутбук разряжается и принудительно перезагружается.
Моя проблема заключалась в том, что я использовал Gas Mask (файловый менеджер hosts для Mac), и у меня не было записи для localhost в файле hosts, который я использовал.
И это решило мою проблему.
Я не совсем уверен, почему, но моя установка Postgres была немного испорчена, и некоторые файлы были удалены, что привело к отображению ошибки OP.
Я просмотрел документацию postgres и обнаружил, что мой файл /usr/local/var/postgres полностью пуст. Итак, я выполнил следующее:
Похоже, что с этой командой произошли некоторые настройки.
Затем он попросил меня запустить это:
И это подсказало мне, что файл postmaster.pid уже существует.
Мне просто нужно было знать, сможет ли brew подобрать конфигурации, которые я только что запустил, поэтому я проверил это.
Это показал мне файл postmaster.pid. Я тогда сделал brew services stop postgresql , и файл postmaster.pid исчез. Потом я это сделал brew services start postgresql , и VIOLA, файл снова появился.
Затем я запустил свое приложение, которое действительно нашло сервер, но, похоже, мои базы данных исчезли.
Хотя я знаю, что они могут вообще не исчезнуть - новая инициализация, которую я сделал, могла создать новую data_area, а старая не указывается. Мне пришлось бы посмотреть, где это, и указать на это снова или просто снова создать свои базы данных.
Надеюсь это поможет! Мне очень помогло чтение документов postgres. Ненавижу читать ответы вроде «Вставьте это, работает!» потому что я не знаю, что, черт возьми, происходит и почему.
I would check where postmaster is trying to create the pid and check if postgres has permission to write to the folder.
Then Maybe change the location for pid creation.
Check also postgreslog and see if you can spot the error.
Grant Instruments (Cambridge) Ltd
Company registered in England, registration number 658133
Registered office address:
29 Station Road,
Shepreth,
CAMBS SG8 6GB
UK
From: [mailto:] On Behalf Of Kranti™ K K Parisa
Sent: 28 January 2010 08:11
To:
Subject: [ADMIN] URGENT :: FATAL: could not create lock file "postmaster.pid": Permission denied
FATAL: could not create lock file "postmaster.pid": Permission denied
getting this error during servic startup.
please suggest quickly as its a production database
thanks in advance.
Best Regards,
Kranti K K Parisa
P Please consider the environment before printing this email
CONFIDENTIALITY: The information in this e-mail and any attachments is confidential. It is intended only for the named recipients(s). If you are not the named recipient please notify the sender immediately and do not disclose the contents to another person or take copies.
VIRUSES: The contents of this e-mail or attachment(s) may contain viruses which could damage your own computer system. Whilst Grant Instruments (Cambridge) Ltd has taken every reasonable precaution to minimise this risk, we cannot accept liability for any damage which you sustain as a result of software viruses. You should therefore carry out your own virus checks before opening the attachment(s).
OpenXML: For information about the OpenXML file format in use within Grant Instruments please visit our website
Thanks for the quick reply. Could you please guide me where could I check the settings or so to identify where postmaster is trying to create the pid file?
Best Regards,
Kranti K K Parisa
I would check where postmaster is trying to create the pid and check if postgres has permission to write to the folder.
Then Maybe change the location for pid creation.
Check also postgreslog and see if you can spot the error.
R
Grant Instruments (Cambridge) Ltd
Company registered in England, registration number 658133
Registered office address:
29 Station Road,
Shepreth,
CAMBS SG8 6GB
UK
From: [mailto: ] On Behalf Of Kranti™ K K Parisa
Sent: 28 January 2010 08:11
To:
Subject: [ADMIN] URGENT :: FATAL: could not create lock file "postmaster.pid": Permission denied
FATAL: could not create lock file "postmaster.pid": Permission denied
getting this error during servic startup.
please suggest quickly as its a production database
thanks in advance.
Best Regards,
Kranti K K Parisa
P Please consider the environment before printing this email
CONFIDENTIALITY: The information in this e-mail and any attachments is confidential. It is intended only for the named recipients(s). If you are not the named recipient please notify the sender immediately and do not disclose the contents to another person or take copies.
VIRUSES: The contents of this e-mail or attachment(s) may contain viruses which could damage your own computer system. Whilst Grant Instruments (Cambridge) Ltd has taken every reasonable precaution to minimise this risk, we cannot accept liability for any damage which you sustain as a result of software viruses. You should therefore carry out your own virus checks before opening the attachment(s).
OpenXML: For information about the OpenXML file format in use within Grant Instruments please visit our website
How are you trying to start the postgres service?
Which user are you trying to start it with?
Grant Instruments (Cambridge) Ltd
Company registered in England, registration number 658133
Registered office address:
29 Station Road,
Shepreth,
CAMBS SG8 6GB
UK
Thanks for the quick reply. Could you please guide me where could I check the settings or so to identify where postmaster is trying to create the pid file?
Best Regards,
Kranti K K Parisa
On Thu, Jan 28, 2010 at 1:44 PM, Renato Oliveira > wrote:
I would check where postmaster is trying to create the pid and check if postgres has permission to write to the folder.
Then Maybe change the location for pid creation.
Check also postgreslog and see if you can spot the error.
Renato Oliveira
Systems Administrator
e-mail:
Grant Instruments (Cambridge) Ltd
Company registered in England, registration number 658133
Registered office address:
29 Station Road,
Shepreth,
CAMBS SG8 6GB
UK
From: [mailto: ] On Behalf Of Kranti™ K K Parisa
Sent: 28 January 2010 08:11
To:
Subject: [ADMIN] URGENT :: FATAL: could not create lock file "postmaster.pid": Permission denied
FATAL: could not create lock file "postmaster.pid": Permission denied
getting this error during servic startup.
please suggest quickly as its a production database
thanks in advance.
Best Regards,
Kranti K K Parisa
P Please consider the environment before printing this email
CONFIDENTIALITY : The information in this e-mail and any attachments is confidential. It is intended only for the named recipients(s). If you are not the named recipient please notify the sender immediately and do not disclose the contents to another person or take copies.
VIRUSES: The contents of this e-mail or attachment(s) may contain viruses which could damage your own computer system. Whilst Grant Instruments (Cambridge) Ltd has taken every reasonable precaution to minimise this risk, we cannot accept liability for any damage which you sustain as a result of software viruses. You should therefore carry out your own virus checks before opening the attachment(s).
OpenXML : For information about the OpenXML file format in use within Grant Instruments please visit our website
P Please consider the environment before printing this email
CONFIDENTIALITY: The information in this e-mail and any attachments is confidential. It is intended only for the named recipients(s). If you are not the named recipient please notify the sender immediately and do not disclose the contents to another person or take copies.
VIRUSES: The contents of this e-mail or attachment(s) may contain viruses which could damage your own computer system. Whilst Grant Instruments (Cambridge) Ltd has taken every reasonable precaution to minimise this risk, we cannot accept liability for any damage which you sustain as a result of software viruses. You should therefore carry out your own virus checks before opening the attachment(s).
OpenXML: For information about the OpenXML file format in use within Grant Instruments please visit our website
i got that, i checked the folder permissions and given full rights to postgres user now i am able to start the service.
Best Regards,
Kranti K K Parisa
How are you trying to start the postgres service?
Which user are you trying to start it with?
R
Grant Instruments (Cambridge) Ltd
Company registered in England, registration number 658133
Registered office address:
29 Station Road,
Shepreth,
CAMBS SG8 6GB
UK
Thanks for the quick reply. Could you please guide me where could I check the settings or so to identify where postmaster is trying to create the pid file?
Best Regards,
Kranti K K Parisa
On Thu, Jan 28, 2010 at 1:44 PM, Renato Oliveira > wrote:
I would check where postmaster is trying to create the pid and check if postgres has permission to write to the folder.
Then Maybe change the location for pid creation.
Check also postgreslog and see if you can spot the error.
R
Renato Oliveira
Systems Administrator
e-mail:
Grant Instruments (Cambridge) Ltd
Company registered in England, registration number 658133
Registered office address:
29 Station Road,
Shepreth,
CAMBS SG8 6GB
UK
From: [mailto: ] On Behalf Of Kranti™ K K Parisa
Sent: 28 January 2010 08:11
To:
Subject: [ADMIN] URGENT :: FATAL: could not create lock file "postmaster.pid": Permission denied
FATAL: could not create lock file "postmaster.pid": Permission denied
getting this error during servic startup.
please suggest quickly as its a production database
thanks in advance.
Best Regards,
Kranti K K Parisa
P Please consider the environment before printing this email
CONFIDENTIALITY : The information in this e-mail and any attachments is confidential. It is intended only for the named recipients(s). If you are not the named recipient please notify the sender immediately and do not disclose the contents to another person or take copies.
VIRUSES: The contents of this e-mail or attachment(s) may contain viruses which could damage your own computer system. Whilst Grant Instruments (Cambridge) Ltd has taken every reasonable precaution to minimise this risk, we cannot accept liability for any damage which you sustain as a result of software viruses. You should therefore carry out your own virus checks before opening the attachment(s).
OpenXML : For information about the OpenXML file format in use within Grant Instruments please visit our website
P Please consider the environment before printing this email
CONFIDENTIALITY: The information in this e-mail and any attachments is confidential. It is intended only for the named recipients(s). If you are not the named recipient please notify the sender immediately and do not disclose the contents to another person or take copies.
VIRUSES: The contents of this e-mail or attachment(s) may contain viruses which could damage your own computer system. Whilst Grant Instruments (Cambridge) Ltd has taken every reasonable precaution to minimise this risk, we cannot accept liability for any damage which you sustain as a result of software viruses. You should therefore carry out your own virus checks before opening the attachment(s).
OpenXML: For information about the OpenXML file format in use within Grant Instruments please visit our website
Чтобы кто-либо смог обратиться к базе данных, необходимо сначала запустить сервер баз данных. Программа сервера называется postgres .
Если вы используете PostgreSQL в виде готового продукта, в нём наверняка реализована возможность запуска сервера в виде фонового задания так, как это принято в вашей операционной системе. Использовать предоставленную продуктом инфраструктуру для запуска сервера гораздо проще, чем пытаться разобраться, как это сделать самостоятельно. За подробностями обратитесь к документации используемого вами продукта.
Самый прямолинейный вариант запуска сервера вручную — просто выполнить непосредственно postgres , указав расположение каталога данных в ключе -D , например:
В результате сервер продолжит работу на переднем плане. Запускать эту команду следует под именем учётной записи PostgreSQL . Без параметра -D сервер попытается использовать каталог данных, указанный в переменной окружения PGDATA . Если и эта переменная не определена, сервер не запустится.
Однако обычно лучше запускать postgres в фоновом режиме. Для этого можно применить обычный синтаксис, принятый в оболочке Unix:
Важно где-либо сохранять информацию, которую выводит сервер в каналы stdout и stderr , как показано выше. Это полезно и для целей аудита, и для диагностики проблем. (Более глубоко работа с файлами журналов рассматривается в Разделе 25.3.)
Программа postgres также принимает несколько других параметров командной строки. За дополнительными сведениями обратитесь к справочной странице postgres и к следующей Главе 20.
Такой вариант запуска довольно быстро может оказаться неудобным. Поэтому для упрощения подобных задач предлагается вспомогательная программа pg_ctl . Например:
Обычно возникает желание, чтобы сервер баз данных сам запускался при загрузке операционной системы. Скрипты автозапуска для разных систем разные, но в составе PostgreSQL предлагается несколько типовых скриптов в каталоге contrib/start-scripts . Для установки такого скрипта в систему требуются права root.
В различных системах приняты разные соглашения о порядке запуска служб в процессе загрузки. Во многих системах для этого используется файл /etc/rc.local или /etc/rc.d/rc.local . В других применяются каталоги init.d или rc.d . Однако при любом варианте запускаться сервер должен от имени пользователя PostgreSQL , но не root или какого-либо другого пользователя. Поэтому команду запуска обычно следует записывать в форме su postgres -c '. ' . Например:
Ниже приведены более конкретные предложения для нескольких основных ОС. (Вместо указанных нами шаблонных значений необходимо подставить правильный путь к каталогу данных и фактическое имя пользователя.)
Для запуска во FreeBSD воспользуйтесь файлом contrib/start-scripts/freebsd в дереве исходного кода PostgreSQL .
В OpenBSD , добавьте в файл /etc/rc.local следующие строки:
В системах Linux вы можете либо добавить
в /etc/rc.d/rc.local или в /etc/rc.local , либо воспользоваться файлом contrib/start-scripts/linux в дереве исходного кода PostgreSQL .
Используя systemd , вы можете применить следующий файл описания службы (например, /etc/systemd/system/postgresql.service ):
Для использования Type=notify требуется, чтобы сервер был скомпилирован с указанием configure --with-systemd .
Особого внимания заслуживает значение тайм-аута. На момент написания этой документации по умолчанию в systemd принят тайм-аут 90 секунд, так что процесс, не сообщивший о своей готовности за это время, будет уничтожен. Но серверу PostgreSQL при запуске может потребоваться выполнить восстановление после сбоя, так что переход в состояние готовности может занять гораздо больше времени. Предлагаемое значение 0 отключает логику тайм-аута.
В NetBSD можно использовать скрипт запуска для FreeBSD или для Linux , в зависимости от предпочтений.
В Solaris , создайте файл с именем /etc/init.d/postgresql , содержащий следующую стоку:
19.3.1. Сбои при запуске сервера
не означает, что у вас закончилось место на диске. Это значит, что установленное в вашем ядре предельное число семафоров System V меньше, чем количество семафоров, которое пытается создать PostgreSQL . Как и в предыдущем случае можно попытаться обойти эту проблему, запустив сервер с меньшим числом допустимых подключений (max_connections), но в конце концов вам придётся увеличить этот предел в ядре.
mandalorian-one commented Sep 18, 2021 •
I took the time for some debugging and came to the conclusion that this is not the container problem but definitely a host problem
the image startup scripts do several restarts of postgres during the initialization sequence.
It uses 'ls' command to check the postgres pid file exists
But 'ls' command suddenly returns "Permission denied" error for all files.
'ls' uses 'stat' function to invoke file info (like size, date etc), but stat returns permission denied for any file in container fs
It leads to the fact that the script incorrectly determines that postgres is shutdown, and try to restart it, but it is still alive. And we got the error FATAL: lock file "postmaster.pid" already exists
I still don't understand the reason for the error but it's definitely a host problem.
there are two fast solutions
- run container with --privileged flag, it fixes the permission denied problem, but it's probably insecure
- fix the startup script /scripts/env-data.sh in function kill_postgres: a simple, but not very reliable solution is to add sleep command for several seconds, to give the server time to shutdown, or more reliably is to rewrite the function so that it does not use 'ls' command to determine the pid file exists
NyakudyaA commented Apr 26, 2022
This is a host issue. Inside the container the files are owned by postgres and this has a specific UID. On the host docker tries to find the same UID as inside the container. If it doesn't find it randomly choose any user with any UID which then causes this issue.
A permanent fix to this would be to get the container running as none root and also allow passing UID and GID from the host to the container
I am not getting as to why am I getting this error when the server has started. can someone please please help.
My pglog.log file shows the following output:
ps -ef | grep postgres
mandalorian-one commented Sep 21, 2021
And sorry for the beginner question but how did you manage to "rewrite the function so that it does not use 'ls' command to determine the pid file exists" ?
You can clone the repo, change scripts and build the container from sources
Look at the section "Building the image" in this repo readme.
or
as a quick temporary solution, you can just copy any file from your existent container to your local filesystem, change it, and copy it back:
docker cp container_name:/file_path local_fs_path
do some things and then
docker cp local_fs_path container_name:/file_path
then restart the container
docker restart container_name
mandalorian-one commented Sep 18, 2021 •
I took the time for some debugging and came to the conclusion that this is not the container problem but definitely a host problem
the image startup scripts do several restarts of postgres during the initialization sequence.
It uses 'ls' command to check the postgres pid file exists
But 'ls' command suddenly returns "Permission denied" error for all files.
'ls' uses 'stat' function to invoke file info (like size, date etc), but stat returns permission denied for any file in container fs
It leads to the fact that the script incorrectly determines that postgres is shutdown, and try to restart it, but it is still alive. And we got the error FATAL: lock file "postmaster.pid" already exists
I still don't understand the reason for the error but it's definitely a host problem.
there are two fast solutions
- run container with --privileged flag, it fixes the permission denied problem, but it's probably insecure
- fix the startup script /scripts/env-data.sh in function kill_postgres: a simple, but not very reliable solution is to add sleep command for several seconds, to give the server time to shutdown, or more reliably is to rewrite the function so that it does not use 'ls' command to determine the pid file exists
agatheLG123 commented Sep 20, 2021
I tried with different types of volumes but had the same problem each time. And I came to the same conclusion, so I asked to be given root priviledge just to test if it was changing anything. Indeed, for me, docker automatically had root priviledges but I wanting to test if in some case it might not be true. In my current case I copied pasted in my working directory the docker-compose file downloaded by the root user (not the docker-compose.yml ! The actual file you have when you install docker-compose in your computer) , and I am executing it by doing ./docker-compose up --build . Maybe when executing the docker-compose file this way it might not automatically get the root priviledges, but I am still waiting for the administrator to give me the root access.
mandalorian-one commented Sep 19, 2021
@mandalorian-one Does this happen when you are using a host mounted file only or docker volume ?
I used docker volume.
I found several references on the Internet to a similar problem. the general explanation if I understood correctly is that container doesn't have access to Linux block devices (like drives and mount points) where mount points are, but it doesn't explain the problem with the docker volumes
agatheLG123 commented Sep 20, 2021 •
And sorry for the beginner question but how did you manage to "rewrite the function so that it does not use 'ls' command to determine the pid file exists" ? Did you created yourself a branch or did you created a new repository where you could access and change the code. Indeed in my code the only link to the kartoga/postgis repo code is in my docker-compose.yml file:
But I don't directly have access to the scripts. I am sure this is an obvious maneuver but I'm not sure how to proceed.
NyakudyaA commented Sep 19, 2021
I took the time for some debugging and came to the conclusion that this is not the container problem but definitely a host problem
the image startup scripts do several restarts of postgres during the initialization sequence.
It uses 'ls' command to check the postgres pid file exists
But 'ls' command suddenly returns "Permission denied" error for all files.
'ls' uses 'stat' function to invoke file info (like size, date etc), but stat returns permission denied for any file in container fs
It leads to the fact that the script incorrectly determines that postgres is shutdown, and try to restart it, but it is still alive. And we got the error FATAL: lock file "postmaster.pid" already exists
I still don't understand the reason for the error but it's definitely a host problem.
there are two fast solutions
@mandalorian-one Does this happen when you are using a host mounted file only or docker volume ?
agatheLG123 commented Sep 20, 2021
Okk tagging the version in the docker-compose.yml file solved my problem :
19.3.2. Проблемы с подключениями клиентов
Хотя ошибки подключений, возможные на стороне клиента, довольно разнообразны и зависят от приложений, всё же несколько проблем могут быть связаны непосредственно с тем, как был запущен сервер. Описание ошибок, отличных от описанных ниже, следует искать в документации соответствующего клиентского приложения.
Если сервер действительно работает, проверьте, что указываемый клиентом путь сокета (здесь /tmp ) соответствует значению unix_socket_directories.
Читайте также: