4

I have set up a postgres database container and can connect and query it directly using its published port 5434.

The goal is to deploy the test database later and access it via nginx reverse proxy. I don't know what is the best way to connect to a deployed test database. Please advise.

I have tried to connect to a postgres database via nginx reverse proxy using local containers.

Using command:

psql -h localhost -p 5435 -U postgres database_name_container_test

Nginx shows error:

reverse-proxy | 2021/10/29 20:06:57 [info] 32#32: *17 client 172.25.0.1:56630 connected to 0.0.0.0:5435
reverse-proxy | 2021/10/29 20:06:57 [error] 32#32: *17 connect() failed (111: Connection refused) while connecting to upstream, client: 172.25.0.1, server:
0.0.0.0:5435, upstream: "172.25.0.3:5434", bytes from/to client:0/0, bytes from/to upstream:0/0

nginx.conf:

stream {    
    upstream database_test {
        server postgres_test:5434;
    }
    server {
        listen 5435 so_keepalive=on;
        proxy_pass database_test;

    }
}

test_db docker-compose:

services:
  postgres_test:
    container_name: postgres_test
    image: postgis/postgis
    restart: always
    expose:
      - 5432
    ports:
      - 5434:5432
    volumes:
      - ./backup:/backup
      - ./postgres-init-db.sh:/docker-entrypoint-initdb.d/postgres-init-db.sh
      - postgres_test_data:/var/lib/postgresql/data
    env_file:
      - ./.env.postgres
    networks:
      - common-network

volumes:
  postgres_test_data:

networks:
  common-network:
    external:
      name: common-network

reverse-proxy docker-compose:

networks:
  common-network: #name in this docker-compose file
    name: common-network # the actual name of the network

services:

  nginx:
    image: nginx:1.20.1
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
    ports:
      - 80:80
      - 443:443
      - 5435:5435
    container_name: reverse-proxy
    networks:
      - common-network

Additionally I checked postgres configuration files, they seem to be correct:

cat postgresql.conf | grep listen_addresses
listen_addresses = '*'


cat pg_hba.conf | grep host
host all all all md5

1 Answer 1

0

When connecting to the Docker container by name, you should use the exposed port of a service, i.e. 5432, as you are connecting directly to the guest:

        server postgres_test:5432;

On the other hand, the published port 5434 becomes present on the host, so you should be able to access the services this way too:

        server localhost:5434;

Which I do not recommend, as you should need to account the port mapping for the future administration (instead of just knowing the container name and a standard exposed port).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .