Skip to content

Spring Boot, Docker and MySQL

flowchart LR
    A[Spring Boot Container] -->|JDBC| B[(MySQL Container)]
    C[MySQL Workbench] -->|Port 3306| B
FROM eclipse-temurin:17-jdk-jammy
WORKDIR /app
COPY target/myapp.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","app.jar"]
version: "3.8"
services:
app:
build: .
container_name: springboot-app
ports:
- "8080:8080"
depends_on:
- mysql
environment:
SPRING_DATASOURCE_URL: jdbc:mysql://mysql:3306/coredb
SPRING_DATASOURCE_USERNAME: root
SPRING_DATASOURCE_PASSWORD: root
mysql:
image: mysql:8.0
container_name: mysql-db
restart: always
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: coredb
ports:
- "3306:3306"
volumes:
- mysqldata:/var/lib/mysql
volumes:
mysqldata:

Inside Docker, localhost refers to the current container.

flowchart LR
    A[Spring Container localhost] -.X.-> B[MySQL Container]
    A -->|mysql service name| B

Use:

spring.datasource.url=jdbc:mysql://mysql:3306/coredb

Not:

spring.datasource.url=jdbc:mysql://localhost:3306/coredb
Terminal window
docker compose up --build

Detached mode:

Terminal window
docker compose up -d

Stop:

Terminal window
docker compose down

Remove volumes:

Terminal window
docker compose down -v
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: coredb

MYSQL_DATABASE automatically creates coredb the first time the MySQL data directory is initialized.

Use these connection details:

Setting Value
Host localhost
Port 3306
Username root
Password root

If port 3306 is already in use, map another host port:

ports:
- "3307:3306"

Then connect Workbench to port 3307.

CREATE TABLE employee (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
salary VARCHAR(255),
version BIGINT
);

Insert sample data:

INSERT INTO employee (name, salary, version)
VALUES
('Abirami','50000',0),
('John','60000',0),
('Alice','70000',0);

View data:

SELECT * FROM employee;
Unable to determine Dialect without JDBC metadata

Possible causes:

  • Wrong JDBC URL
  • MySQL container not running
  • Using localhost inside Docker
  • Database not yet ready

Recommended property:

spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect

(MySQL8Dialect was removed in Hibernate 6 / Spring Boot 3 — use MySQLDialect, or omit the property entirely and let Hibernate auto-detect the dialect from the JDBC connection.)

  • Use Docker Compose for application + database.
  • Use named volumes for persistence.
  • Use MySQL Workbench as the desktop client.
  • Avoid mixing host databases with containerized applications.
  • Docker Compose creates networking automatically.
  • Use the Compose service name as the database host.
  • MYSQL_DATABASE creates the database on first initialization.
  • MySQL Workbench connects through the exposed host port.