首页 > 解决方案 > 适用于 Linux 2 的 Windows 子系统:Ubuntu,连接到外部 PostgreSQL 数据库

问题描述

我正在使用 Ubuntu 18.04 运行适用于 Linux 2 (WSL-2) 的新 Windows 子系统。它真的很快,而且运行得很好,除了我似乎无法使用 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 Server 数据库。我确定两个服务器的凭据都是正确的,它们直接来自我在其他系统上使用得很好的 Django 设置文件。有任何想法吗?我有什么psycopg2专门针对 WSL-2 的吗?

标签: pythonpostgresqlubuntupsycopg2windows-subsystem-for-linux

解决方案


所以事实证明我把手指指向了错误的方向。

我和同事一起登录 PostgreSQL 服务器,并发出以下命令:

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

事实证明,与服务器的现有连接很好,但有些东西卡住了。我有一堆空闲进程,然后是一堆说“启动等待”的进程——超过 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过程中出现了一些问题,这导致新连接挂起,而没有失败。是时候深入挖掘并清理它了,但是这种行为有答案。


推荐阅读