title: Connecting two a database in a another container with docker-compose
body: <p>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.</p>
  
  <pre><code>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:
  </code></pre>
  
  <p>I also tried it with setting network driver to <code>bridge</code> (which didn't change the end result)</p>
  
  <pre><code>networks:
    backend:
      driver: bridge
  </code></pre>
  
  <p>I'm using the following url to connect to the database</p>
  
  <pre><code>spring.datasource.url=jdbc:postgresql://psqldb:5432/mydb
  </code></pre>
  
  <p>I also tried to expose the port and connect using <code>localhost</code></p>
  
  <pre><code>spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
  </code></pre>
  
  <p>I also tried to use port 5433 instead of 5432.</p>
  
  <p>No matter what combination I used, I got the following error</p>
  
  <pre><code>Connection to psqldb:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
  </code></pre>
  
  <p>in my app container. However, my database container remains up and I can connect to it fine from host with the url</p>
  
  <pre><code>spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
  </code></pre>
  
  <p>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).</p>
  
  <p>If it makes any difference, I'm using Spring 
  Boot for application with the Dockerfile</p>
  
  <pre><code>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"]
  </code></pre>
  
  <p>and I'm building the image with the command</p>
  
  <pre><code>docker build --build-arg JAR_FILE=target/*.jar -t dsb .
  </code></pre>
  
  <p>What am I missing in the two container setup?</p>