我们有一个运行在 AWS EC2 实例中的 PostgreSQL 数据库。我们的目标是从运行到运行在 AWS EKS 集群内的 EC2 节点的 Docker 容器连接到该数据库。我们使用 Python (
pyodbc
) 来连接数据库。
我们得到这个错误:
2023-02-23T15:03:49.532858159Z return pyodbc.connect(connection_str)
2023-02-23T15:03:49.532902079Z pyodbc.OperationalError: ('08001', '[08001] could not connect to server: Network is unreachable\n\tIs the server running on host "****" and accepting\n\tTCP/IP connections on port 5432?\ncould not connect to server: Network is unreachable\n\tIs the server running on host "5432" (0.0.21.56) and accepting\n\tTCP/IP connections on port 5432?\n (101) (SQLDriverConnect)')
我们使用 Putty 访问了 EKS EC2 节点。当我们运行相同的 Python 代码连接数据库时,连接成功。
我们认为 Docker 容器存在连接问题。但是我们无法弄清楚这个问题。
这是构建Docker镜像时使用的
docker-compose.yaml
文件。
version: "3.7"
services:
dev:
image: dbimage
container_name: dbimage
build:
context: .
target: dbimage
args:
- BUILDKIT_INLINE_CACHE=1
- BUILD_DATE
- GITREF
networks:
- cloud-network
volumes:
- .:/app
networks:
cloud-network:
driver: bridge
这通过在
--network host
命令中添加docker run
选项来解决。