0

I have Spring app where I want to connect with MySQL db. I'm creating MySQL container using docker-compose.yml file:

version: '3.7'
services:
  my-backend:
    container_name: my-app
    image: app
    environment:
      - _JAVA_OPTIONS=-Xmx512m -Xms256m
      - SPRING_PROFILES_ACTIVE=dev
    ports:
      - "8010:8080"
    build:
      context: .
      dockerfile: "Dockerfile"
    depends_on:
      - db

  db:
    container_name: mysql-app
    image: mysql:5.7
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=root
      - MYSQL_USER=my_user
      - MYSQL_PASSWORD=my_pass
      - MYSQL_DATABASE=my_db
    ports:
      - "3307:3306"
    volumes:
      - mysql:/var/lib/mysql

volumes:
  mysql:

And there is application.yml file:

spring:
  datasource:
    url:jdbc:mysql://localhost:3307/my_db?serverTimezone=UTC&enabledTLSProtocols=TLSv1.2
    username: root
    password: root

When I want to connect to the db on port 3307 it is not possible because I've got error:

The driver has not received any packets from the server.

Connection refused

So my my guess falls on wrong port, but when I'm using phpMyAdmin this connects with db without problem.

Piotror
  • 85
  • 1
  • 12
  • Where is the Spring application running; in another container, outside a container but on the same host, somewhere else? – David Maze Jun 15 '22 at 10:52
  • 1
    Configure `SPRING_DATASOURCE_URL=jdbc:mysql://db:3306/my_db?...`. The database is not `localhost` (the Spring container believes `localhost` is the Spring container) and connections between containers ignore `ports:`. – David Maze Jun 15 '22 at 11:14
  • Thanks this works, but what about application.yml? I don't need to configure spring datasource like url, username and password? – Piotror Jun 15 '22 at 11:29
  • A `src/main/resources/application.yml` file gets compiled into your jar file; it's not a good place to put deployment-specific settings like this. I'd recommend using Spring's ability to set properties from environment variables here, and provide a Compose `environment: {SPRING_DATASOURCE_URL: ...}`. – David Maze Jun 15 '22 at 11:41
  • Yeah I know, but for example I want to debug app using Intellij and how to specify datasource url when MySQL container is running on port 3307 locally and then I've get error that it can not connect with db using this url **jdbc:mysql://localhost:3307/my_db** – Piotror Jun 15 '22 at 11:52
  • The URL will be different running in a container and running from your IDE outside a container. – David Maze Jun 15 '22 at 13:55

0 Answers0