Postgresql Docker角色不存在

2024-06-16 14:07:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我下载了postgres的docker容器:https://hub.docker.com/r/library/postgres/,并执行了以下操作:

$ docker run --name satgres -e POSTGRES_PASSWORD=mysecretpassword -d -p 5432:5432 postgres
satgres | "docker-entrypoint.s…" | 5 seconds ago | Up 6 seconds | 0.0.0.0:5432->5432/tcp | satgres
$ docker exec -it c8f1b22cc41e /bin/bash        
# psql -U postgres
psql (10.1)
postgres=# CREATE DATABASE mytest;
postgres=# \password postgres
postgres=# CREATE ROLE ming WITH LOGIN PASSWORD 'pass1234';
postgres=# ALTER ROLE ming CREATEDB;
postgres=# CREATE DATABASE sjk;
postgres=# GRANT ALL PRIVILEGES ON DATABASE youtube TO ming;
postgres=# \connect sjk
youtube=# ALTER ROLE ming lOGIN;  

我的计划是在docker和Django上使用这个数据库,所以首先要检查我是否可以连接,但我不能

$ psql -h localhost -p 5432 -U postgres
$ psql: FATAL:  role "postgres" does not exist
$ psql -h localhost -p 5432 -U ming
$ psql: FATAL:  role "ming" does not exist

我对PSequal.app也做了同样的事情, 我在Mac High Sierra上跑步

为什么我会犯这个错误?这个角色存在,或者至少在我看来


Tags: dockerlocalhostyoutubecreatepostgrespassworddatabaserole
2条回答

问题很简单,我的计算机已经运行了一个Postgres实例,但我不知道该实例仍在:5432上运行(不在Docker内部),请检查:

$ lsof -n -i:5432 | grep LISTEN

所以我记得我是通过https://gist.github.com/sgnl/609557ebacd3378f3b72安装的,我运行

$ pg-stop

然后我就可以连接到Docker实例了

编辑(2019/07/02)

这个问题最近通过了10000个视图,所以我想我应该详细说明为什么会发生这种情况

通常通过docker运行,使用python并连接到postgres数据库需要您通过pip3 install psycopg2安装psycopg2,但如果您运行此命令,您将获得:

Error: pg_config executable not found.

这是因为psycopg2需要在操作系统上安装postgres库:

yum install postgresql-devel
apt-get install postgresql-client

现在,在Mac电脑上,您需要对brew执行同样的操作:

brew install postgresql

有一件事我没有意识到,在Mac上,执行上述操作不仅会安装所需的库,而且还会在:5432上启动数据库。因为这都是在后台完成的,所以我没有想到这是问题所在,因为没有出现任何常见错误来通知端口正在使用,等等

在我的例子中,这个问题也可能是由于使用了一个不是postgres的超级用户。开发者在Georgechestra docker组合中选择了用户Georgechestra。 从dockerfile中提取:

environment:
  - POSTGRES_USER=georchestra

HEALTHCHECK  interval=30s  timeout=30s \
  CMD pg_isready -U $POSTGRES_USER

因此,您必须使用选项“-U georchestra”连接到容器

$ docker exec -it docker_database_1 psql -U georchestra
psql (10.5 (Debian 10.5-1.pgdg90+1))
Type "help" for help.

当然,尝试与用户postgres连接会导致错误:

docker exec -it docker_database_1 psql -U postgres
psql: FATAL:  role "postgres" does not exist

相关问题 更多 >