# 能否从独立应用程序直接连接到数据库？

**URL:** <https://meta.discourse.org/t/is-it-possible-to-connect-to-the-database-directly-from-a-separate-app/152695>\
**Category:** Self-hosting\
**Created:** [2020年五月25日 21:52 UTC](https://meta.discourse.org/t/is-it-possible-to-connect-to-the-database-directly-from-a-separate-app/152695 "2020-05-25T21:52:58Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![AstonJ](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/astonj/32/215041_2.png) [@AstonJ](https://meta.discourse.org/u/AstonJ)\
**Post date:** [2020年五月27日 01:56 UTC](https://meta.discourse.org/t/is-it-possible-to-connect-to-the-database-directly-from-a-separate-app/152695/6 "2020-05-27T01:56:00Z")

</div>

有人知道为什么这不起作用吗？

我参考了 @pfaffman 和 @Nacho_Caballero 在这个主题中的帖子：[https://meta.discourse.org/t/how-to-make-the-database-or-part-of-it-accessible-to-a-cloud-data-processor/147915，以及](https://meta.discourse.org/t/how-to-make-the-database-or-part-of-it-accessible-to-a-cloud-data-processor/147915%EF%BC%8C%E4%BB%A5%E5%8F%8A) @mpalmer 在这个主题中的帖子：[Accessing to the database from outside the container - #4 by mpalmer](https://meta.discourse.org/t/accessing-to-the-database-from-outside-the-container/45257/4?u=astonj%E3%80%82)

首先，我编辑了 app.yml，添加以下内容：

```plaintext
expose:
  - "127.0.0.2:5432:5432"

```

然后重建容器。在容器内，我为 postgres 用户设置了密码，并可以通过以下命令从容器内部连接：

```plaintext
psql -h localhost -d discourse -U postgres

```

但是，当我退出容器并尝试连接时，却收到以下错误：

```plaintext
# psql -h 127.0.0.2 -p 5432 -d discourse -U postgres
psql: server closed the connection unexpectedly
	This probably means the server terminated abnormally
	before or while processing the request.

```

我也尝试将端口更改为其他值，但结果相同。我从 `docker ps` 和检查网络设置中获取了 127 IP（我有三个独立运行的 Discourse 实例）。

如果我更改 IP（改为另一个 Discourse 论坛的 IP），则会收到一个（更直接且）不同的响应/消息，这表明上述操作部分正确：

```plaintext
# psql -h 127.0.0.3 -p 5432 -d discourse -U postgres
psql: could not connect to server: Connection refused
	Is the server running on host "127.0.0.3" and accepting
	TCP/IP connections on port 5432?

```

有人知道我在哪里出错了吗？搜索 `psql: server closed the connection unexpectedly` 似乎表明这是一个网络问题——我是否需要在容器内更改其他设置？

---

_[View the full topic](https://meta.discourse.org/t/is-it-possible-to-connect-to-the-database-directly-from-a-separate-app/152695)._
