Ошибка postgresql template1

I need to create database.

First I run: sudo su - postgres, then: createdb test

And I keep getting this error:

createdb: could not connect to database template1: 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"

This is unexpected, I have never encountered any problems with psql, but this time I don’t get what is wrong. And there is no external server, I am connected locally.

I am running on Ubuntu.

halfer's user avatar

halfer

19.8k17 gold badges98 silver badges185 bronze badges

asked May 7, 2015 at 8:20

pptt's user avatar

5

The error means that the Postgres server is not running. Try starting it:

sudo systemctl start postgresql

I believe the service name is postgresql, but if that doesn’t work, try typing

sudo systemctl start postgres

and pressing tab to auto-complete.

Make sure that the server starts on boot:

sudo systemctl enable postgresql

answered Feb 11, 2020 at 12:13

Vikram Jain's user avatar

Vikram JainVikram Jain

5,4701 gold badge19 silver badges31 bronze badges

1

The error message suggests:

Is the server running locally

and according to the result of ps -ef | grep "post" posted in the comments, the answer is a definitive No, the server processes are not there, the server is not running.

That fact that you write i have never encountered any problems with psql, suggests that it was installed and working before, in that case look at the most recent log file inside /var/log/postgresql to check for any fatal error message indicating why the server didn’t start.

answered May 7, 2015 at 10:31

Daniel Vérité's user avatar

Daniel VéritéDaniel Vérité

57.4k15 gold badges127 silver badges152 bronze badges

  1. Install and run postgreSQL

createdb -h localhost -p 5432 -U postgres testdb password ******

answered Feb 11, 2020 at 11:45

Aishwarya kabadi's user avatar

1

In my case, I did the following to get rid of this error:

sudo apt remove --purge postgres*
sudo apt remove --purge pg*   #optional
sudo apt autoremove
sudo apt autoclean
sudo apt clean

Then…

sudo apt update
sudo apt upgrade
sudo apt install -y postgresql-10 postgresql-contrib postgresql-client
sudo apt install -y postgresql-server pgadmin4 ] -> this you may need for metasploit
sudo reboot

And finally, after checking if Postgresql has been installed, if its down, then do this:

List all the Postgres clusters running on your device:
pg_lsclusters

Restart the pg_ctlcluster:
sudo pg_ctlcluster 10 main start

Restart PostgreSQL service:
sudo service postgresql restart

answered Nov 29, 2021 at 16:48

Singh's user avatar

SinghSingh

4824 silver badges14 bronze badges

I logged in to source database template1 and now I can’t create database.
When I try to create database, I get this error:

OperationalError: source database "template1" is being accessed by other users
DETAIL:  There are 5 other session(s) using the database.

Every time I login to template1, I use ‘exit’ command to logout, but as you can see it does not logout and number of sessions increases everytime I login. Is there a way to force disconnect every connection to template1 that logged in now?

asked Jan 17, 2013 at 8:18

Andrius's user avatar

3

Database template1 exists only to provide barebone structure to create another empty database. You should never logon to template1, otherwise you will have problems.

Probably easiest solution for you is to restart PostgreSQL server process, and logon again. Database that should always exist and is safe to logon is postgres.

If restarting is not an option, you can use another emergency template database: template0.

By default, this statement:

CREATE DATABASE dbname;

is equivalent to:

CREATE DATABASE dbname TEMPLATE template1;

If template1 is not available or corrupted, you can use template0 as last resort:

CREATE DATABASE dbname TEMPLATE template0;

You can read more about template databases here.

answered Jan 17, 2013 at 8:25

mvp's user avatar

mvpmvp

110k13 gold badges121 silver badges147 bronze badges

11

This helped me solve my problem:

SELECT *, pg_terminate_backend(procpid) 
FROM pg_stat_activity 
WHERE usename='username';

--Use pid if PostgreSQL version 9.2 or above.

I terminated all active connections to template1 and could create database normally

answered Jan 17, 2013 at 9:27

Andrius's user avatar

AndriusAndrius

19.2k36 gold badges142 silver badges238 bronze badges

6

You can also try to terminate the current process thread by the Terminal

Search the Process :

sudo ps aux | grep template1

Kill the Process :

sudo kill -9 < your process id >

answered May 14, 2016 at 10:23

DASADIYA CHAITANYA's user avatar

2

To solve this, I have to disconnect the database connection from the
pgAdmin III.

answered Jul 28, 2015 at 16:25

roxdurazo's user avatar

roxdurazoroxdurazo

74510 silver badges21 bronze badges

0

I have a script that connects to a database and performs various operations on it, some requiring that no one else is logged in. I modified @Andrius’s answer not to terminate my script’s connection, but rather terminate everyone else’s:

SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE pid <> pg_backend_pid();

From the docs: pg_backend_pid() is the Process ID of the server process attached to the current session.

answered Mar 22, 2018 at 0:44

Cloud Artisans's user avatar

Cloud ArtisansCloud Artisans

3,9983 gold badges30 silver badges37 bronze badges

If you are using the PgAdminn, you can manually set the definitions provided in the image.

enter image description here

answered Jan 5, 2021 at 1:26

Arefe's user avatar

ArefeArefe

11k18 gold badges108 silver badges165 bronze badges

  1. enter pgAdmin
  2. right-click to server
  3. disconnect server
  4. again connect server
  5. do what you want

answered Jun 16, 2020 at 10:05

Aqil Aghamirzayev's user avatar

0

You need to kill all the connections to the template database and leave other connections uninterrupted, so use the following query to kill all the connections to templateDb

    SELECT 
    pg_terminate_backend(pid) 
FROM 
    pg_stat_activity 
WHERE 
    -- don't kill my own connection!
    pid <> pg_backend_pid()
    -- don't kill the connections to other databases
    AND datname = 'templateDb'
    ;

Then use the usual query to copy the templateDb

CREATE DATABASE dbname TEMPLATE templateDb ;

answered Aug 17, 2022 at 22:53

M.Ali El-Sayed's user avatar

This problem occur when you had logged(psql template1 or psql template0) in template1 and template0 database and exit using below command.

Ctrl + z

Better way exist from db use below postgres command then problem will not create:

q + enter

There are 2 solutions, If have problem.

Solution — 1

Restart posgres service like.

sudo service postgresql restart

Solution — 2

sudo ps aux | grep template1

Make sure don’t delete this processes

postgres 8363 0.0 0.0 111760 7832 pts/11 T 09:49 0:00 /usr/lib/postgresql/9.5/bin/psql template1
ankit 18119 0.0 0.0 14224 976 pts/14 S+ 12:33 0:00 grep —color=auto template1

rest of process should be kill using below command.

sudo kill -9

Now try to create db again.

Hope this help you.

Ankit H Gandhi.

answered Nov 1, 2017 at 7:42

Er.Ankit H Gandhi's user avatar

1

If you use pgadmin4 or similar tools, makes sure it is either doing the create database itself or that it’s shut off.

I had generated a create database with pgadmin4 then used its scripting functionality to export the script it used, which I then copied and altered to put it in my own automated scripts.

Problem was that the active webpage pgadmin somehow ended up on database template1.

Stopping and restarting the server itself didn’t fix anything, pgadmin was smart enough to reconnect to the server as soon as it came back up.

answered Oct 30, 2020 at 15:56

JL Peyret's user avatar

JL PeyretJL Peyret

10.7k2 gold badges52 silver badges71 bronze badges

You can try to restart the postgresql service that is running in the background.

answered Feb 17, 2017 at 19:12

ezzadeen's user avatar

ezzadeenezzadeen

1,02510 silver badges9 bronze badges

On Windows I had to reinstall PostgreSQL, restart did not help.

answered May 16, 2019 at 14:17

Tomas Kubes's user avatar

Tomas KubesTomas Kubes

23.5k18 gold badges109 silver badges147 bronze badges

if you go to the side panel , browser, servers, database, then on the right is a summary of the database…becareful here, there is a press right and find the dropdown to delete the database, so if sure, get rid of existing database, and create a new one, so that you can claim ownership of the newly created one

answered Dec 29, 2019 at 22:57

Fioat N's user avatar

In windows. shutdown the GUI. do it from psql command prompt.

answered Jan 20, 2020 at 13:00

Anupam Kumar's user avatar

I had a same problem but after googling, I understood I have a connection to (postgis_30_sample) database (the template that I want to copy from). This connection was created by GeoServer when I created some stores in Geo Server application.

So I Stopped the service and the issue was fixed !
enter image description here

answered Feb 25, 2020 at 23:54

Mostafa Fallah's user avatar

I have solved problem like this via reconnecting to the server (pgAdmin -> disconnect -> connect)

answered Aug 9, 2020 at 16:28

Tim  Uzlov's user avatar

Tim UzlovTim Uzlov

1712 silver badges6 bronze badges

I have the same problem with:
ERROR: source database «template1» is being accessed by other users
DETAIL: There is 1 other session using the database.

And i Solved the problem in postgreSQL 13 by clicking in the left column on PostgreSQL 13 where the tables showing some graphs appeared. I was interested in the sever activity table, here I found a line that contained the word template1 and I turned it off with a cross, then restarted the application here and everything works.

error: template1-solved

answered Oct 26, 2020 at 13:09

PixiePin's user avatar

If you are using Docker, have to set host to ‘0.0.0.0’ than ‘localhost’ in your sequelize config.

answered Nov 4, 2020 at 0:45

Eduardo Vieira's user avatar

1

I came across almost same problem. Solution I found is—> «closed dbeaver GUI on my UBUNTU machine and used terminal to create database(lc_db1) using my other database(lc_db) as a TEMPLATE by using following command—>

    CREATE DATABASE lc_db1 TEMPLATE lc_db;

Output of this code is:—>

answered Mar 14, 2022 at 21:44

Nikhil Patil's user avatar

1

Проблема простая и причина ошибки сразу указана в тексте ошибки:

Эта база данных используется ещё в 1 сеансе.

Посмотреть какие это сессии можно запросом:

select * from pg_stat_activity where datname = 'template1';

Принудительно их завершить запросом:

select pg_terminate_backend(pid) from pg_stat_activity where datname = 'template1';

После завершения всех сессий к этой базе create database успешно выполнится.


Непонятна здесь может деталь, при чём тут какой-то template1 когда вы командуете, допустим,

create database newdb;

Где тут template1 и как для создания новой пустой БД мешают сессии в template1?

Фокус здесь в том, что вообще-то create database не умеет создавать новые базы с нуля из ничего. Это умеет только initdb при инициализации всего экземпляра postgresql. А create database умеет только создавать копию базы указанную параметром template со значением по-умолчанию как раз template1. При этом, чтобы не получить несогласованное состояние файлов базы из-за параллельного изменения этой базы кем-то ещё create database требует, чтобы никто к этой template базе не был подключен вообще.

#ruby-on-rails #windows #postgresql #ubuntu #ruby-on-rails-5

#ruby-on-rails #Windows #postgresql #убунту #ruby-on-rails-5

Вопрос:

После удаления и установки несколько раз я сталкиваюсь со следующей ошибкой, кажется, я просто не могу заставить postgresql работать. Я пытаюсь настроить среду программирования для ruby on rails 6 в Windows 10. Я следил за следующими статьями и проделал весь путь до создания пользователя, где я получаю следующие ошибки.

ссылки на то, как я сюда попал

https://github.com/serivas/wsl2_rails_setup

https://gorails.com/setup/windows/10#ruby-rbenv

https://www.postgresql.org/download/linux/ubuntu/

Ошибка, которую я получаю при вводе

 sudo -u postgres createuser abc -s
 

Сообщение об ошибке;

 createuser: error: could not connect to database template1: 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"?
 

Заранее спасибо!

Комментарии:

1. Похоже, Postgres не работает?

2. да, я думаю, мы оба можем согласиться с этим…. Есть идеи, почему? Кто-нибудь укажет мне правильное направление?

3. Как и вы, я тоже здесь в ловушке.

4. @Lancer. Ян, ознакомьтесь с моим ответом, чтобы узнать, как я решил эту проблему.

Ответ №1:

Вот как я решил свою проблему для всех, у кого могли возникнуть подобные проблемы.

  • Убедитесь, что ваша Windows 10 обновлена, чтобы иметь возможность запускать WSL2
  • Сначала перейдите по ссылке ниже, чтобы установить Ruby и Rails.
  • https://gorails.com/setup/windows/10
  • Настройте PostgreSQL по ссылке выше,
  • ссылка ниже также поможет мне настроить PostgreSQL;
  • https://docs.microsoft.com/en-us/windows/wsl/tutorials/wsl-database

Если у вас возникли проблемы с входом в Postgres, убедитесь, что вы создали пользователя в Postgres, который позволяет пользователю иметь возможность CREATEDB. Поэтому, если вашим пользователем является JohnDoe, убедитесь, что вы даете разрешение JohnDoe на создание базы данных.

Ссылки, которые помогут вам с предоставлением разрешения.

  • https://dba.stackexchange.com/questions/33285/granting-a-user-account-permission-to-create-databases-in-postgresql

Убедитесь, что вы запускаете свой сервер postgresql.

sudo service postgresql start

И остановить

sudo service postgresql stop

После того, как пользователь получит права на создание базы данных, вы можете продолжить и ввести

rake db:create

Комментарии:

1. Большое вам спасибо за ваше уведомление. Позже я попробую следующие методы. Кажется, работает для меня.

Я вошел в исходный шаблон базы данных1, и теперь я не могу создать базу данных. Когда я пытаюсь создать базу данных, я получаю эту ошибку:

OperationalError: source database "template1" is being accessed by other users
DETAIL:  There are 5 other session(s) using the database.

Каждый раз, когда я вхожу в систему для шаблона1, я использую команду «exit» для выхода из системы, но, как вы видите, она не выходит из системы, и количество сеансов увеличивается каждый раз, когда я вхожу в систему. Есть ли способ принудительно отключить каждое соединение с шаблоном1, которое теперь входит в систему?

4b9b3361

Ответ 1

Это помогло мне решить мою проблему:

SELECT *, pg_terminate_backend(procpid) 
FROM pg_stat_activity 
WHERE usename='username';

--Use pid if PostgreSQL version 9.2 or above.

Я прекратил все активные подключения к шаблону1 и мог нормально создавать базу данных

Ответ 2

template1 базы template1 существует только для обеспечения barebone-структуры для создания еще одной пустой базы данных. Вы никогда не должны подключаться к template1, иначе у вас возникнут проблемы.

Вероятно, самое простое решение для вас — перезапустить серверный процесс PostgreSQL и снова войти в систему. База данных, которая всегда должна существовать и безопасна для входа в систему, — postgres.

Если перезапуск не является вариантом, вы можете использовать другую базу данных template0 аварийных событий: template0.

По умолчанию это утверждение:

CREATE DATABASE dbname;

эквивалентно:

CREATE DATABASE dbname TEMPLATE template1;

Если template1 недоступен или поврежден, вы можете использовать template0 качестве последнего средства:

CREATE DATABASE dbname TEMPLATE template0;

Вы можете узнать больше о базах данных шаблонов здесь.

Ответ 3

Чтобы решить эту проблему, я должен отключить соединение с базой данных из pgAdmin III.

Ответ 4

Вы также можете попытаться завершить текущий поток процесса с помощью терминала

Поиск в процессе:

sudo ps aux | grep template1

Убейте процесс:

sudo kill -9 <ваш идентификатор процесса>

Ответ 5

У меня есть сценарий, который соединяется с базой данных и выполняет различные операции над ним, некоторые требуют, чтобы никто другой не вошел в систему. Я изменил @Andrius, чтобы не прерывать соединение с моим скриптом, а скорее разорвать все остальные:

SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE pid <> pg_backend_pid();

Из документов: pg_backend_pid() — это идентификатор процесса серверного процесса, подключенного к текущему сеансу.

Ответ 6

Эта проблема возникает, когда вы вошли в систему (psql template1 или psql template0) в базе данных template1 и template0 и выходите с помощью команды ниже.

Ctrl + z

Лучше всего существует использование db ниже команды postgres, тогда проблема не создаст:

q + введите

Есть 2 решения, если есть проблема.

Решение — 1

Перезапустите службу посмертов.

sudo service postgresql restart

Решение — 2

sudo ps aux | grep template1

Не удаляйте эти процессы

postgres 8363 0.0 0.0 111760 7832 pts/11 T 09:49 0:00/usr/lib/postgresql/9.5/bin/psql template1 ankit 18119 0.0 0.0 14224 976 pts/14 S+ 12:33 0:00 grep [CN00 ] = автоматический шаблон1

остальная часть процесса должна быть убита с помощью команды ниже.

sudo kill -9

Теперь попробуйте создать db снова.

Надеюсь, это поможет вам.

Анкит Х Ганди.

Ответ 7

На Windows мне пришлось переустанавливать PostgreSQL, перезапуск не помог.

Ответ 8

Вы можете попробовать перезапустить службу postgresql, которая работает в фоновом режиме.

Понравилась статья? Поделить с друзьями:
  • Ошибка po327 лада калина
  • Ошибка post gelf
  • Ошибка po505 лансер 9
  • Ошибка po304 приора
  • Ошибка post error occurs как исправить