PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, October 18, 2022

[FIXED] When running psql in a Docker container, how to do I reference my Postgres host in another Docker container?

 October 18, 2022     docker, docker-compose, postgresql, psql     No comments   

Issue

I have the following two containers in my docker-compose.yml file

  postgres:
    image: postgres:10.5
    ports:
      - 5105:5432
    ...
  web:
    restart: always
    build: ./web
    ports:           # to access the container from outside
      - "8000:8000"
    env_file: .env
    command: /usr/local/bin/gunicorn directory.wsgi:application --reload -w 1 -b :8000
    volumes:
    - ./web/:/app
    depends_on:
      - postgres

When I'm logged in to my "web" container (an Ubuntu 18 container), I'd like to be able to login to the PostGres container. How do I do this? I tried this

root@0868cef9c65c:/my-app# PGPORT=5432 PGPASSWORD=password psql -h localhost -Uchicommons directory_data
psql: error: could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?
could not connect to server: Cannot assign requested address
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 5432?

but this doesn't seem to be working.


Solution

In a Docker container, localhost refers to the container itself.

By default, Docker compose creates a docker bridge network and connects each container to it. From a container on the bridge network, you can reach other containers using their service names. So to reach the database container, you'd use postgres as the host name, like this

PGPORT=5432 PGPASSWORD=password psql -h postgres -Uchicommons directory_data

On the bridge network, you use the native ports. So it's port 5432 for Postgres. If you only need to access a container from other containers on the bridge network, you don't need to map the port to a host port. Mapping to a host port is only needed if you need to access the container from the host computer.



Answered By - Hans Kilian
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing