You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Postgres容器中用init脚本创建多用户遇角色不存在问题

问题:PostgreSQL初始化用户后连接提示“Role X does not exist”

部署配置(Docker Compose)

version: "3.9"
services:
  postgres:
    image: postgres
    secrets:
      - pg_user_secret
      - pg_password_secret
    environment:
      POSTGRES_USER_FILE: /run/secrets/pg_user_secret
      POSTGRES_PASSWORD_FILE: /run/secrets/pg_password_secret
    deploy:
      placement:
        constraints: [node.role == manager]
    volumes:
      - ./postgres/init.sql:/docker-entrypoint-initdb.d/init.sql
      - postgres-data:/var/lib/postgresql/data

  adminer:
    image: adminer:latest
    ports:
      - 8080:8080

volumes:
  postgres-data:

secrets:
  pg_user_secret:
    file: './pg_user.txt'
  pg_password_secret:
    file: './pg_password.txt'x

初始化脚本(init.sql)

CREATE USER authUser WITH PASSWORD 'authPassword';
CREATE USER portfoliosUser WITH PASSWORD 'portfoliosPassword';
CREATE USER ordersUser WITH PASSWORD 'ordersPassword';

CREATE DATABASE auth;
REVOKE CONNECT ON DATABASE auth FROM PUBLIC;
GRANT CONNECT ON DATABASE auth TO authUser;
GRANT ALL PRIVILEGES ON DATABASE auth to authUser;

CREATE DATABASE portfolios;
REVOKE CONNECT ON DATABASE portfolios FROM PUBLIC;
GRANT CONNECT ON DATABASE portfolios TO authUser;
GRANT CONNECT ON DATABASE portfolios TO portfoliosUser;
GRANT ALL PRIVILEGES ON DATABASE portfolios to authUser;
GRANT ALL PRIVILEGES ON DATABASE portfolios to portfoliosUser;

CREATE DATABASE orders;
REVOKE CONNECT ON DATABASE orders FROM PUBLIC;
GRANT CONNECT ON DATABASE orders TO ordersUser;
GRANT ALL PRIVILEGES ON DATABASE orders to ordersUser;

问题现象

使用脚本中创建的用户(如authUser)连接PostgreSQL时,收到错误:Role X does not exist.

问题原因

PostgreSQL对未用双引号包裹的标识符(包括用户名、数据库名等),默认会自动转换为小写。因此脚本中的authUser实际被创建为authuser,当你用驼峰格式的authUser尝试连接时,PostgreSQL会去查找同名的小写角色,自然找不到,从而抛出角色不存在的错误。

内容的提问来源于stack exchange,提问作者Stefan Nastase

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 21:07:11