繁体   English   中英

Postgres 和 Docker:数据库错误 - 角色“用户名”不存在

[英]Postgres and Docker: Database error - role “username” does not exist

我试图在 MacOS 上实现配置这个项目的 postgres 数据库,所以我安装了 postgres、docker 并尝试在这个 docker 文件上运行docker-compose up -d

version: "3"

services:
  maadb-ps-db:
    image: postgres:latest
    container_name: maadb-ps-db
    ports:
      - "5433:5432"
    env_file:
      - postgres.env
    volumes:
      - database-data:/usr/local/var/postgres

volumes:
  database-data:

这里我的环境文件只有这一行:

POSTGRES_HOST_AUTH_METHOD=trust

然后,我尝试通过python和以下方法连接到数据库:

def get_resources_sql():
conn = None
try:
    # read connection parameters
    params = config()

    # connect to the PostgreSQL server
    print('Connecting to the PostgreSQL database...')
    conn = psycopg2.connect(**params)

    # create a cursor
    cur = conn.cursor()

    # TODO

    # close the communication with the PostgreSQL
    cur.close()
except (Exception, psycopg2.DatabaseError) as error:
    print("Database ERROR: ", error)
finally:
    if conn is not None:
        conn.close()
        print('Database connection closed.')

参数如下:

[postgresql]
host=localhost
port=5433
database=maadbsql

当我尝试运行代码时,出现以下错误:

args {'host': 'localhost', 'port': '5433', 'database': 'maadbsql'}
Connecting to the PostgreSQL database...
Database ERROR:  FATAL:  role "username" does not exist

如果我尝试通过psql maadbsql打开 maadbsql 数据库并检查权限,这就是我得到的(我只有两个用户,“用户名”和“postgres”):

在此处输入图片说明

我错过了什么吗?

编辑:

这是运行docker-compose up后的日志:链接

这是关机后的日志:链接

我认为您没有适当地创建数据库。 我首先删除您的容器和卷:

docker-compose down -v

配置您的环境文件,以便 postgres 映像将为您的应用程序创建一个数据库和用户:

POSTGRES_HOST_AUTH_METHOD=trust
POSTGRES_USER=maadbsql
POSTGRES_DB=maadbsql

通过此更改,我可以成功运行以下 Python 代码:

>>> import psycopg2
>>> conn = psycopg2.connect('dbname=maadbsql user=maadbsql host=localhost port=5433')
>>> cur = conn.cursor()
>>> cur.execute('create table example(id int, name text)')
>>> conn.commit()
>>> cur.execute('insert into example (id, name) values (%s, %s)', (1, 'alice'))
>>> conn.commit()
>>> cur.execute('select * from example')
>>> cur.fetchall()
[(1, 'alice')]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM