> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-zh.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 连接外部 PostgreSQL 数据库

LangSmith 使用 PostgreSQL 数据库作为事务性工作负载和操作数据（除了运行记录之外的几乎所有数据）的主要数据存储。默认情况下，LangSmith 自托管版将使用内部 PostgreSQL 数据库。但是，您可以配置 LangSmith 以使用外部 PostgreSQL 数据库。通过配置外部 PostgreSQL 数据库，您可以更轻松地管理数据库的备份、扩展和其他操作任务。

<Tip>
  **如果您使用托管的 PostgreSQL 服务**，我们推荐：

  * [Amazon RDS](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_GettingStarted.CreatingConnecting.PostgreSQL.html) (AWS)
  * [Google Cloud SQL](https://cloud.google.com/curated-resources/cloud-sql#section-1) (GCP)
  * [Azure Database for PostgreSQL](https://azure.microsoft.com/en-us/products/postgresql#features) (Azure)

  关于云服务商特定的 IAM/工作负载身份认证，请参阅 [IAM 认证部分](#iam-authentication)。
</Tip>

## 要求

* 一个已部署的 PostgreSQL 数据库，您的 LangSmith 实例需要能够通过网络访问它。我们建议使用托管的 PostgreSQL 服务，例如：

  * [Amazon RDS](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_GettingStarted.CreatingConnecting.PostgreSQL.html)
  * [Google Cloud SQL](https://cloud.google.com/curated-resources/cloud-sql#section-1)
  * [Azure Database for PostgreSQL](https://azure.microsoft.com/en-us/products/postgresql#features)

* 注意：我们仅官方支持 PostgreSQL 版本 >= 14。

* 我们支持密码认证和 [IAM/工作负载身份](#iam-authentication) 认证。

* 一个对 PostgreSQL 数据库具有管理员访问权限的用户。此用户将用于创建必要的表、索引和模式。

* 此用户还需要能够在数据库中创建扩展。我们使用/将尝试安装 `btree_gin`、`btree_gist`、`pgcrypto`、`citext`、`ltree` 和 `pg_trgm` 扩展。

* 如果使用非 public 的模式，请确保没有其他启用了这些扩展的模式，或者您必须将其包含在搜索路径中。

* 对 pgbouncer 和其他连接池的支持是基于社区的。社区成员报告称，pgbouncer 在 `pool_mode` = `session` 以及合适的 `ignore_startup_parameters` 设置下可以工作（截至撰写时，需要忽略 `search_path` 和 `lock_timeout`）。需要注意避免污染连接池；建议具备一定程度的 PostgreSQL 专业知识。LangChain Inc 目前没有将 pgbouncer 或 amazon rds proxy 或任何其他连接池的正式测试覆盖或商业支持纳入路线图计划，但欢迎社区通过 GitHub issues 讨论和协作支持。

* 默认情况下，我们推荐一个**至少具有 2 个 vCPU 和 8GB 内存**的实例。但是，实际要求将取决于您的工作负载和用户数量。我们建议监控您的 PostgreSQL 实例并根据需要进行扩展。

## 连接字符串

您需要提供 PostgreSQL 数据库的连接字符串。此连接字符串应包含以下信息：

* 主机
* 端口
* 数据库
* 用户名
* 密码（如果有任何特殊字符，请确保进行 URL 编码）- **注意：** 使用 IAM 认证时，连接字符串中不需要密码。详见下文。
* URL 参数

其格式如下：

```
用户名:密码@主机:端口/数据库?<url参数>
```

一个示例连接字符串可能如下所示：

```
myuser:mypassword@myhost:5432/mydatabase?sslmode=disable
```

如果没有 URL 参数，连接字符串将如下所示：

```
myuser:mypassword@myhost:5432/mydatabase
```

对于 IAM 认证，省略密码，并使用身份名称作为用户名：

```
my-workload-identity@myhost:5432/mydatabase?sslmode=require
```

## 配置

准备好连接字符串后，您可以配置您的 LangSmith 实例以使用外部 PostgreSQL 数据库。您可以通过修改 LangSmith Helm Chart 安装的 `values` 文件或 Docker 安装的 `.env` 文件来实现。

<CodeGroup>
  ```yaml Helm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  postgres:
    external:
      enabled: true
      connectionUrl: "您的连接URL"
  ```

  ```bash Docker theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  # 在您的 .env 文件中
  POSTGRES_DATABASE_URI="您的连接URL"
  ```
</CodeGroup>

配置完成后，您应该能够重新安装 LangSmith 实例。如果一切配置正确，您的 LangSmith 实例现在应该正在使用您的外部 PostgreSQL 数据库。

## 与 PostgreSQL 的 TLS

使用本节配置 PostgreSQL 连接的 TLS。关于挂载内部/公共 CA 以使 LangSmith 信任您的 PostgreSQL 服务器证书，请参阅 [配置自定义 TLS 证书](/langsmith/self-host-custom-tls-certificates#mount-internal-cas-for-tls)。

### 服务器 TLS（单向）

要验证 PostgreSQL 服务器证书：

* 使用 `config.customCa.secretName` 和 `config.customCa.secretKey` 提供 CA 包。
* 在连接 URL 中使用 `sslmode=require` 或 `sslmode=verify-full`，以及 `sslrootcert=system`。

<Warning>
  仅当您的 PostgreSQL 服务器使用内部或私有 CA 时才挂载自定义 CA。公开信任的 CA 不需要此配置。
</Warning>

<CodeGroup>
  ```yaml Helm (服务器 TLS) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  config:
    customCa:
      secretName: "langsmith-custom-ca"  # 包含您的 CA 包的 Secret
      secretKey: "ca.crt"    # Secret 中包含 CA 包的键
  postgres:
    external:
      enabled: true
      connectionUrl: "myuser:mypassword@myhost:5432/mydatabase?sslmode=verify-full&sslrootcert=system"
      customTls: true
  ```

  ```yaml Kubernetes Secret (CA 包) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  apiVersion: v1
  kind: Secret
  metadata:
    name: langsmith-custom-ca
  type: Opaque
  stringData:
    ca.crt: |
      -----BEGIN CERTIFICATE-----
      <根证书或中间CA证书链>
      -----END CERTIFICATE-----
  ```
</CodeGroup>

### 双向 TLS 与客户端认证 (mTLS)

自 LangSmith helm chart 版本 **0.12.29** 起，我们支持 PostgreSQL 客户端的 mTLS。对于 mTLS 中的服务器端认证，除了以下客户端证书配置外，还需使用 [服务器 TLS 步骤](#server-tls-one-way)（自定义 CA）。

如果您的 PostgreSQL 服务器要求客户端证书认证：

* 提供一个包含您的客户端证书和密钥的 Secret。
* 通过 `postgres.external.clientCert.secretName` 引用它，并使用 `certSecretKey` 和 `keySecretKey` 指定密钥。
* 在连接 URL 中使用 `sslmode=verify-full` 和 `sslrootcert=system`。

<CodeGroup>
  ```yaml Helm (客户端认证) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  postgres:
    external:
      enabled: true
      connectionUrl: "myuser:mypassword@myhost:5432/mydatabase?sslmode=verify-full&sslrootcert=system"
      customTls: true
      clientCert:
        secretName: "postgres-mtls-secret"
        certSecretKey: "tls.crt"
        keySecretKey: "tls.key"
  ```

  ```yaml Kubernetes Secret (客户端证书/密钥) theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  apiVersion: v1
  kind: Secret
  metadata:
    name: postgres-mtls-secret
  type: Opaque
  stringData:
    tls.crt: |
      -----BEGIN CERTIFICATE-----
      <客户端证书>
      -----END CERTIFICATE-----
    tls.key: |
      -----BEGIN PRIVATE KEY-----
      <客户端密钥>
      -----END PRIVATE KEY-----
  ```
</CodeGroup>

#### 证书卷的 Pod 安全上下文

为 mTLS 挂载的证书卷受文件访问限制保护。为确保所有 LangSmith pod 都能读取证书文件，您必须在 pod 安全上下文中设置 `fsGroup: 1000`。

您可以通过以下两种方式之一进行配置：

**选项 1：使用 `commonPodSecurityContext`**

在顶层设置 `fsGroup` 以应用于所有 pod：

```yaml theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
commonPodSecurityContext:
  fsGroup: 1000
```

**选项 2：添加到各个 pod 的安全上下文**

如果需要更精细的控制，请将 `fsGroup` 单独添加到每个 pod 的安全上下文中。有关完整参考，请参阅 [mTLS 配置示例](https://github.com/langchain-ai/helm/blob/main/charts/langsmith/examples/mtls_config.yaml)。

## IAM 认证

自 LangSmith helm chart 版本 **0.12.34** 起，我们支持 PostgreSQL 的 IAM 认证。这允许您使用云服务商的工作负载身份代替静态密码。

<Warning>
  IAM 认证仅处理连接认证。您可能仍然需要在数据库中运行 SQL 命令来创建 IAM 用户/角色，并授予其访问 LangSmith 模式所需的权限和特权。
</Warning>

<Tabs>
  <Tab title="AWS">
    <a id="amazon-rds" />

    ### Amazon RDS IAM 认证

    Amazon RDS 支持 [IAM 数据库认证](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html)，允许您使用 AWS IAM 凭证而不是数据库密码来验证 PostgreSQL 实例。

    #### 先决条件

    1. 使用 [AWS IRSA](https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html) 或 [EKS Pod Identity](https://docs.aws.amazon.com/eks/latest/userguide/pod-identities.html) 在您的 Kubernetes 集群中**配置工作负载身份**
    2. 在您的 RDS PostgreSQL 实例上**启用 IAM 认证**并向您的工作负载身份授予访问权限

    #### 配置

    <Warning>
      如果在 LangSmith 已运行初始迁移后切换到新的 IAM 用户，您可能需要将现有表的所有权转移给新的 IAM 用户。否则，由于先前用户拥有的表权限不足，迁移可能会失败。
    </Warning>

    将 `iamAuthProvider` 设置为 `"aws"` 并提供 IAM 兼容的连接字符串（无密码）：

    ```yaml theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    postgres:
      external:
        enabled: true
        existingSecretName: "postgres-secret"
        iamAuthProvider: "aws"
    ```

    ```yaml theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    apiVersion: v1
    kind: Secret
    metadata:
      name: postgres-secret
    type: Opaque
    stringData:
      # IAM 连接 URL - 注意没有密码，用户名是 IAM 身份名称
      connection_url: "<iam-identity-name>@<rds-host>:5432/<database>?sslmode=require"
    ```

    <Warning>
      IAM 认证需要 TLS。您必须在连接字符串中包含 `sslmode=require`。
    </Warning>

    #### 必需的注解

    您必须将 AWS IRSA 所需的 ServiceAccount 注解应用到所有连接到 PostgreSQL 的 LangSmith 组件：

    **部署：** `backend`、`queue`、`platformBackend`、`hostBackend`、`ingestQueue`

    **作业：** `migrations`、`authBootstrap`、`feedbackConfigMigration`、`feedbackDataMigration`、`e2eTest`

    <Note>
      上面列出的所有作业（除了 `e2eTest`）都使用 `backend` 服务账户。`e2eTest` 作业使用自己的服务账户，需要单独的注解配置。
    </Note>

    后端服务的示例配置：

    ```yaml theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    backend:
      serviceAccount:
        annotations:
          eks.amazonaws.com/role-arn: "arn:aws:iam::<account-id>:role/<role-name>"

    queue:
      serviceAccount:
        annotations:
          eks.amazonaws.com/role-arn: "arn:aws:iam::<account-id>:role/<role-name>"

    platformBackend:
      serviceAccount:
        annotations:
          eks.amazonaws.com/role-arn: "arn:aws:iam::<account-id>:role/<role-name>"

    hostBackend:
      serviceAccount:
        annotations:
          eks.amazonaws.com/role-arn: "arn:aws:iam::<account-id>:role/<role-name>"

    ingestQueue:
      serviceAccount:
        annotations:
          eks.amazonaws.com/role-arn: "arn:aws:iam::<account-id>:role/<role-name>"
    ```

    有关可配置服务的完整列表，请参阅 [Helm values 参考](https://github.com/langchain-ai/helm/blob/main/charts/langsmith/values.yaml)。
  </Tab>

  <Tab title="GCP">
    <a id="google-cloud-sql" />

    ### Cloud SQL IAM 认证

    Cloud SQL 支持 [IAM 认证](https://cloud.google.com/sql/docs/postgres/iam-authentication)，允许您使用 GCP 服务账户而不是数据库密码进行认证。

    #### 先决条件

    1. 使用 [GCP Workload Identity](https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity) 在您的 Kubernetes 集群中**配置工作负载身份**
    2. 在您的 Cloud SQL 实例上**启用 IAM 认证**并向您的工作负载身份授予访问权限

    #### 配置

    <Warning>
      如果在 LangSmith 已运行初始迁移后切换到新的 IAM 用户，您可能需要将现有表的所有权转移给新的 IAM 用户。否则，由于先前用户拥有的表权限不足，迁移可能会失败。
    </Warning>

    将 `iamAuthProvider` 设置为 `"gcp"` 并提供 IAM 兼容的连接字符串（无密码）：

    ```yaml theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    postgres:
      external:
        enabled: true
        existingSecretName: "postgres-secret"
        iamAuthProvider: "gcp"
    ```

    ```yaml theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    apiVersion: v1
    kind: Secret
    metadata:
      name: postgres-secret
    type: Opaque
    stringData:
      # IAM 连接 URL - 注意没有密码，用户名是服务账户邮箱
      connection_url: "<service-account>@<project>.iam@<cloud-sql-host>:5432/<database>?sslmode=require"
    ```

    <Warning>
      IAM 认证需要 TLS。您必须在连接字符串中包含 `sslmode=require`。
    </Warning>

    #### 必需的注解

    您必须将 GCP Workload Identity 所需的 ServiceAccount 注解应用到所有连接到 PostgreSQL 的 LangSmith 组件：

    **部署：** `backend`、`queue`、`platformBackend`、`hostBackend`、`ingestQueue`

    **作业：** `migrations`、`authBootstrap`、`feedbackConfigMigration`、`feedbackDataMigration`、`e2eTest`

    <Note>
      上面列出的所有作业（除了 `e2eTest`）都使用 `backend` 服务账户。`e2eTest` 作业使用自己的服务账户，需要单独的注解配置。
    </Note>

    后端服务的示例配置：

    ```yaml theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    backend:
      serviceAccount:
        annotations:
          iam.gke.io/gcp-service-account: "<service-account>@<project>.iam.gserviceaccount.com"

    queue:
      serviceAccount:
        annotations:
          iam.gke.io/gcp-service-account: "<service-account>@<project>.iam.gserviceaccount.com"

    platformBackend:
      serviceAccount:
        annotations:
          iam.gke.io/gcp-service-account: "<service-account>@<project>.iam.gserviceaccount.com"

    hostBackend:
      serviceAccount:
        annotations:
          iam.gke.io/gcp-service-account: "<service-account>@<project>.iam.gserviceaccount.com"

    ingestQueue:
      serviceAccount:
        annotations:
          iam.gke.io/gcp-service-account: "<service-account>@<project>.iam.gserviceaccount.com"
    ```

    有关可配置服务的完整列表，请参阅 [Helm values 参考](https://github.com/langchain-ai/helm/blob/main/charts/langsmith/values.yaml)。
  </Tab>

  <Tab title="Azure">
    <a id="azure-database-for-postgresql" />

    ### Azure Database for PostgreSQL 与 Microsoft Entra 认证

    Azure Database for PostgreSQL 支持 [Microsoft Entra 认证](https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/concepts-azure-ad-authentication)，允许您使用 Azure 托管标识而不是数据库密码进行认证。

    #### 先决条件

    1. 使用 [Azure Workload Identity](https://learn.microsoft.com/en-us/azure/aks/workload-identity-overview) 在您的 Kubernetes 集群中**配置工作负载身份**
    2. 在您的 Azure Database for PostgreSQL 实例上**启用 Microsoft Entra 认证**并向您的工作负载身份授予访问权限

    #### 配置

    <Warning>
      如果在 LangSmith 已运行初始迁移后切换到新的 IAM 用户，您可能需要将现有表的所有权转移给新的 IAM 用户。否则，由于先前用户拥有的表权限不足，迁移可能会失败。
    </Warning>

    将 `iamAuthProvider` 设置为 `"azure"` 并提供 IAM 兼容的连接字符串（无密码）：

    ```yaml theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    postgres:
      external:
        enabled: true
        existingSecretName: "postgres-secret"
        iamAuthProvider: "azure"
    ```

    ```yaml theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    apiVersion: v1
    kind: Secret
    metadata:
      name: postgres-secret
    type: Opaque
    stringData:
      # IAM 连接 URL - 注意没有密码，用户名是托管标识名称
      connection_url: "<managed-identity-name>@<azure-postgres-host>:5432/<database>?sslmode=require"
    ```

    <Warning>
      IAM 认证需要 TLS。您必须在连接字符串中包含 `sslmode=require`。
    </Warning>

    #### 必需的注解和标签

    您必须将 Azure Workload Identity 所需的 ServiceAccount 注解和 pod 标签应用到所有连接到 PostgreSQL 的 LangSmith 组件：

    **部署：** `backend`、`queue`、`platformBackend`、`hostBackend`、`ingestQueue`

    **作业：** `migrations`、`authBootstrap`、`feedbackConfigMigration`、`feedbackDataMigration`、`e2eTest`

    <Note>
      上面列出的所有作业（除了 `e2eTest`）都使用 `backend` 服务账户。对于这些作业，您只需要配置 pod 标签（Azure 要求在 pod 上设置 `azure.workload.identity/use: "true"`）。`e2eTest` 作业使用自己的服务账户，需要单独的注解配置。
    </Note>

    后端服务的示例配置：

    ```yaml theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    backend:
      serviceAccount:
        annotations:
          azure.workload.identity/client-id: "<managed-identity-client-id>"
      deployment:
        labels:
          azure.workload.identity/use: "true"
      migrations:
        labels:
          azure.workload.identity/use: "true"

    queue:
      serviceAccount:
        annotations:
          azure.workload.identity/client-id: "<managed-identity-client-id>"
      deployment:
        labels:
          azure.workload.identity/use: "true"

    platformBackend:
      serviceAccount:
        annotations:
          azure.workload.identity/client-id: "<managed-identity-client-id>"
      deployment:
        labels:
          azure.workload.identity/use: "true"

    hostBackend:
      serviceAccount:
        annotations:
          azure.workload.identity/client-id: "<managed-identity-client-id>"
      deployment:
        labels:
          azure.workload.identity/use: "true"

    ingestQueue:
      serviceAccount:
        annotations:
          azure.workload.identity/client-id: "<managed-identity-client-id>"
      deployment:
        labels:
          azure.workload.identity/use: "true"
    ```

    有关可配置服务的完整列表，请参阅 [Helm values 参考](https://github.com/langchain-ai/helm/blob/main/charts/langsmith/values.yaml)。
  </Tab>
</Tabs>

***

<div className="source-links">
  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\langsmith\self-host-external-postgres.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>

  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>
</div>
