简体   繁体   中英

Docker-compose can't connect to Docker postgres container

My Postgres DB is running in a Docker container. When container is started, it says it's ready to listen on 5432. My application container is set to depend on it.

    container_name: my_postgres_db
    image: library/postgres:latest
    network_mode: bridge
    expose:
      - 5432
    ports:
      - 5432:5432
    environment:
      - POSTGRES_USER=admin
      - POSTGRES_PASSWORD=admin
      - POSTGRES_DB=localdb
    restart: always

The config for app:

    container_name: my_test_app
    depends_on:
      - db
    build:
      context: ./
      dockerfile: Dockerfile
    image: my_test_app
    ports:
      - 8080:8080

Based on solutions to the similar questions, I changed the localhost in the DB URL to: spring.datasource.url=jdbc:postgresql://db:5432/localdb

It causes another error = "Unknown host exception". Even if I manage to build app this way, it still doesn't work. Logs say, Connection to localhost:5432 refused What else am I missing? Why is it still listening to localhost:5432 when I obviously changed it to db:5432 and gradlew clean/build it?

just change the network_mode in postgres and app to host

network_mode: host

note that this will ignore the expose option and will use the host network an containers network

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM