简体   繁体   中英

Connecting two a database in a another container with docker-compose

I'm trying to set up a docker-compose where one container has the database and the other one has the application. To my best knowledge, I need to connect two containers with a network.

version: "3"
services:
  psqldb:
    image: "postgres"
    container_name: "psqldb"
    environment:
      - POSTGRES_USER=usr
      - POSTGRES_PASSWORD=pwd
      - POSTGRES_DB=mydb
    ports:
      - "5432:5432"
    expose:
      - "5432"
    volumes:
      - $HOME/docker/volumes/postgres/:/var/lib/postgresql/data
    networks:
      - backend
  sbapp:
    image: "dsb"
    container_name: "dsb-cont"
    ports:
      - "8080:8080"
    expose:
      - "8080"
    depends_on:
      - psqldb
    networks:
      - backend

networks:
  backend:

I also tried it with setting network driver to bridge (which didn't change the end result)

networks:
  backend:
    driver: bridge

I'm using the following url to connect to the database

spring.datasource.url=jdbc:postgresql://psqldb:5432/mydb

I also tried to expose the port and connect using localhost

spring.datasource.url=jdbc:postgresql://localhost:5432/mydb

I also tried to use port 5433 instead of 5432.

No matter what combination I used, I got the following error

Connection to psqldb:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

in my app container. However, my database container remains up and I can connect to it fine from host with the url

spring.datasource.url=jdbc:postgresql://localhost:5432/mydb

I can also connect to the database from host if I remove psqldb container entirely from docker-compose.yml (and use the latter connection url).

If it makes any difference, I'm using Spring Boot for application with the Dockerfile

FROM openjdk:8-jdk-alpine
VOLUME /tmp
ARG JAR_FILE
COPY ${JAR_FILE} app.jar
EXPOSE 8080
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom", "-jar", "app.jar"]

and I'm building the image with the command

docker build --build-arg JAR_FILE=target/*.jar -t dsb .

What am I missing in the two container setup?

The issue I had was that docker depends_on only starts the containers in the defined order but doesn't wait for them to be actually ready.

https://docs.docker.com/compose/startup-order/

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