Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker Compose + Postgres: Expose port

I am currently trying to use Docker for my new Django/Postgres project. I am working on a Mac and usually use Postico to quickly connect to my database.

I used to connect like here:

enter image description here

I used the official Docker documentation to setup docker-compose. I now have the issue, that I can't connect via Postico to the postgres db. It seems to me that the problem comes from the ports not being exposed.

enter image description here

version: '3'

services:
  db:
    image: postgres
  web:
    build: .
    command: python3 manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db
like image 862
Joey Coder Avatar asked Sep 29 '18 10:09

Joey Coder


2 Answers

Just map the port to the host machine, add this to the db service in your Compose file:

ports:
  - "5432:5432"

Also make sure to set the postgres password variable in the compose file like this

environment:
  POSTGRES_PASSWORD: example

The default user is postgres, you can change it with the POSTGRES_USER variable.

You can read about the usage of the image with all options here: https://hub.docker.com/_/postgres/

like image 81
takacsmark Avatar answered Sep 18 '22 14:09

takacsmark


By default Compose sets up a single network for your app.

Each container can be accessed by the name of the service in the compose file.

In your case you don't have to expose the port to the host machine for your web app to have access to it. You can simply use db as the hostname for postgres (and 5432 for the port) from any other service running on the same compose.

Actually a very similar example is provided in the docker compose documentation: https://docs.docker.com/compose/networking/

like image 39
Alexis_A Avatar answered Sep 21 '22 14:09

Alexis_A