0

I have a Spring Boot application which connects to a MariaDB database. I am trying to run docker-compose for those two services but I get the following error:

java.sql.SQLNonTransientConnectionException: Socket fail to connect to host:address=(host=maria_db)(port=10000)
(type=primary). maria_db
...
Caused by: java.net.UnknownHostException: maria_db

Here is my docker-compose.yml file:

version: "3.7"
services:
  api_service:
    build: .
    restart: always
    ports:
      - "8080:8080"
    depends_on:
      - maria_db
  maria_db:
    image: "mariadb:10.5.8"
    restart: always
    ports:
      - "10000:3306"
    environment:
      MYSQL_DATABASE: app_db
      MYSQL_USER: exampleuser
      MYSQL_PASSWORD: examplepass
      MYSQL_ROOT_PASSWORD: examplepass

Here is my Dockerfile for the Spring app:

FROM openjdk:17-oracle
COPY target/app-0.0.1.jar app-0.0.1.jar
RUN ["java","-jar","/app-0.0.1.jar"]

Here is my application.properties file:

spring.datasource.url=jdbc:mariadb://maria_db:10000/app_db
spring.datasource.username=exampleuser
spring.datasource.password=examplepass
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
springdoc.api-docs.path = /javainuse-openapi

I am new to docker, but every resource on the topic I have found so far seems to suggest this setup. What am I doing wrong?

I am using:

  • Spring Boot 3.0.2,
  • Java 17,
  • Docker Engine v20.10.22 (Docker Windows)
MilanJ
  • 5
  • 4
  • Inside docker network you have to use the maria_db docker port (3306). If you wish to maintain the config separately use application-docker.properties and configure your docker port and url(maria_db:3306) there. – mallikarjun Feb 22 '23 at 18:47
  • @mallikarjun Thank you for the comment. I have tried that, but it throws the same exception... – MilanJ Feb 22 '23 at 20:01
  • You're trying to `RUN` the application as part of the image build. This is the wrong point in time. Mechanically, the image build doesn't run on the Compose network, and that's why you're getting that specific error. Change this to the `CMD` the container will run when it starts up. – David Maze Feb 23 '23 at 00:38
  • (Also see [Difference between RUN and CMD in a Dockerfile](https://stackoverflow.com/questions/37461868/difference-between-run-and-cmd-in-a-dockerfile).) – David Maze Feb 23 '23 at 00:40

1 Answers1

0

You may need to add networks property, try this:

version: "3.7"
services:
  api_service:
    build: .
    restart: always
    ports:
      - "8080:8080"
    depends_on:
      - maria_db
    networks:
      - docker-net
  maria_db:
    image: "mariadb:10.5.8"
    restart: always
    ports:
      - "10000:3306"
    networks:
      - docker-net
    environment:
      MYSQL_DATABASE: app_db
      MYSQL_USER: exampleuser
      MYSQL_PASSWORD: examplepass
      MYSQL_ROOT_PASSWORD: examplepass

networks:
  docker-net:
    driver: bridge
Murat Yıldız
  • 11,299
  • 6
  • 63
  • 63