Windows Linux 2 的子系统:Ubuntu,连接到外部 PostgreSQL 数据库

Windows Subsystem for Linux 2: Ubuntu, connect to external PostgreSQL database

我是 运行 Linux 2 (WSL-2) 的新 Windows 子系统,Ubuntu 18.04。它真的很快,而且 运行 很棒,除了我似乎无法使用 Python 连接到外部 PostgreSQL 数据库。它只是挂起,从不响应。这是一个最小的复制:

$ python3.6
Python 3.6.8 (default, Jan 14 2019, 11:02:34)
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import psycopg2
>>> psycopg2.connect(host="my-pg-server.mydomain.com", port=5432, user="my_user", dbname="my_db", password="")
[...crickets... doesn't time out, just hangs forever (at least an hour)...]

这不是防火墙问题,因为我可以通过 telnet 连接到同一台主机:

$ telnet my-pg-server.mydomain.com 5432
Trying 123.456.789.100...
Connected to my-pg-server.mydomain.com.
Escape character is '^]'.

另一个奇怪的部分是我可以 连接到外部SQL 服务器数据库。我确定两个服务器的凭据都是正确的,它们直接来自我在其他系统上使用得很好的 Django 设置文件。有任何想法吗? psycopg2 有什么我必须专门为 WSL-2 做的吗?

原来我指错了方向。

我和一个同事一起登录到 PostgreSQL 服务器框,并发出了这个命令:

ps -ef --sort=start_time | fgrep [db host name] | more

事实证明,与服务器的 现有 连接正常,但有些东西卡住了。我有一堆空闲进程,然后是一大堆说 "startup waiting" - 超过 100。这是命令的输出:

[...about 100 idle processes, truncated...]
postgres 26815 48821  0 Aug16 ? 00:00:00 postgres: my-pg-server: web_user web 192.168.9.187(55972) idle
postgres 27525 48821  0 Aug16 ? 00:00:00 postgres: my-pg-server: web_user web 192.168.9.187(55976) idle
postgres 14781 48821  0 00:00 ? 00:00:00 postgres: my-pg-server: postgres jsmith_d [local] VACUUM waiting
postgres 22738 48821  0 00:01 ? 00:00:00 postgres: my-pg-server: other_user other_db 192.168.9.187(57692) startup waiting
postgres  7683 48821  0 00:15 ? 00:00:00 postgres: my-pg-server: yetanother_user yetanother_db 192.168.9.187(57694) startup waiting
postgres 15951 48821  0 00:30 ? 00:00:00 postgres: my-pg-server: yetanother_user yetanother_db 192.168.9.187(57696) startup waiting
[...and about another 100 startup waiting processes, truncated...]

啊哈!它发现的罪魁祸首:

postgres 14781 48821 0 00:00 ? 00:00:00 postgres: my-pg-server: postgres jsmith_d [local] VACUUM waiting

VACUUM 进程中似乎出现了问题,这导致新连接只是挂起,而没有失败。是时候更深入地挖掘并清理它了,但这里有解决此问题的方法。