Search code examples
postgresqlamazon-web-servicesdockerkubernetespyodbc

Cannot Connect to an EC2 PostgreSQL Server from a Docker Container running in an AWS EKS Cluster Node


We have a PostgreSQL database running into an AWS EC2 instance. Our target is connecting to this database from a Docker container running into an EC2 node which is running inside an AWS EKS cluster. We use Python (pyodbc) to connect to the database.

We get this error:

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)')

We accessed the EKS EC2 node using Putty. When we run the same Python code for connecting to the database, the connection is successful.

We believe the Docker container has a connectivity issue. But we cannot figure out the issue.

This is the docker-compose.yaml file used when building the Docker image.

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

Solution

  • This is solved by adding the --network host option in the docker run command.