在postgres中创建数据库时出现错误

问题描述:

我想在linux服务器上创建用户和数据库。 我可以用下面的代码创建用户:在postgres中创建数据库时出现错误

su - postgres 
# createuser -S -D -R myUser 

但是当我试图用代码创建数据库:

# createdb -U myUser -p 5432 myDatabase 

我获得以下错误:

createdb: could not connect to database postgres: FATAL: Ident authentication failed for user "myUser" 

我新来的Linux,所以我无法弄清楚为什么我能够创建用户,但创建数据库时,与Postgres的连接错误。对于用户而言,身份验证 也是错误的。

+0

我认为这个问题可能更适合于serverfault或superuser或unix.stackexchange。可能你会在那里得到更好的答案。这个问题与编程没有太大关系(什么是stackoverflow的目的)。 – bmk 2011-05-12 08:40:10

I am new to linux so I am unable to figure out why I was able to create user but while creating database there is connection error with postgres. And also error for ident authentication for user.

的ident是依赖于当前登录的用户的的认证模式。如果你使用了postgres,然后尝试以另一个用户身份登录,ident将会失败(因为它不是当前登录的用户)。你可以用两种方法解决这个问题,我倾向于使用后者。

解决:只需确保当前登录的用户是与你想登录到Postgres的用户:

[email protected]:~$ createuser -S -D -R myUser 
[email protected]:~$ exit 
machine:~# su - myUser 
[email protected]:~$ psql myDatabase 

更好的解决方案:变化的pg_hba.conf(大概位于/etc/postgresql/8.4/main/或类似),并确保将“md5”身份验证模式添加到选项列表中。这是我对我的发展箱的pg_hba.conf,没有评论:

[email protected]:~$ sudo cat /etc/postgresql/8.4/main/pg_hba.conf | grep -v "^#" | grep -v "^$" 
local all   postgres       ident 
local all   all        md5 
host all   all   127.0.0.1/32   md5 
host all   all   ::1/128    md5 

这告诉PostgreSQL的是Postgres的可的ident登录,而所有其他用户可以登录使用MD5认证。这样一来,就可以使用-U切换到PSQL二进制来表示你希望成为其用户,所以实际上的工作原理:

[email protected]:~$ psql -U myUser myDatabase. 

这么说,我倾向于使用Postgres超级用户创建数据库。然后,我将新创建的数据库的权限授予新创建的用户,因此:

[email protected]:~$ psql template1 
template1=# CREATE USER myUser WITH PASSWORD 'myPassword'; 
CREATE ROLE 
template1=# CREATE DATABASE myDatabase; 
CREATE DATABASE 
template1=# GRANT ALL PRIVILEGES ON DATABASE myDatabase TO myUser; 
GRANT 
template1=# \q 

希望有所帮助。

附录:一旦你改变了pg_hba.conf,你将不得不重新启动PostgreSQL服务器,以确保它再次读取配置。您可以通过发出以下命令这样做:

[email protected]:~$ /etc/init.d/postgresql-8.4 restart 

脚本可能会因操作系统和安装的方法被称为“PostgreSQL的”而不是“的PostgreSQL-8.4”。

见例如:this link

请使用谷歌搜索,你给句话...