DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Effective Exception Handling in Microservices Integration
  • Keep Your Application Secrets Secret
  • Smart Deployment Strategies for Modern Applications
  • Building Fault-Tolerant Spring Boot Microservices With Kafka and AWS

Trending

  • Building Enterprise-Grade Real-Time IoT Dashboards with Vue 3, MQTT, and Kafka
  • Ujorm3: A New Lightweight ORM for JavaBeans and Records
  • Ingesting Fixed-Width Mainframe Files Into Delta Lake: The Details Nobody Writes Down
  • From AI Chaos to Control: Building Enterprise-Grade LLM Gateways With MuleSoft Anypoint
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Integrating Spring Boot Microservices With MySQL Container Using Docker Desktop

Integrating Spring Boot Microservices With MySQL Container Using Docker Desktop

Discover a guide for developers on integrating Spring Boot applications with MySQL in Docker Desktop, covering setup steps and practical advice for integration.

By 
Amol Gote user avatar
Amol Gote
DZone Core CORE ·
Apr. 04, 24 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
9.4K Views

Join the DZone community and get the full member experience.

Join For Free

Docker has become an essential tool for developers, offering consistent and isolated environments without installing full-fledged products locally. The ideal setup for microservice development using Spring Boot with MySQL as the backend often involves a remotely hosted database. However, for rapid prototyping or local development, running a MySQL container through Docker offers a more streamlined approach. 

I encountered a couple of issues while attempting to set up this configuration with the help of Docker Desktop for a proof of concept. An online search revealed a lack of straightforward guides on integrating Spring Boot microservices with MySQL in Docker Desktop; most resources primarily focus on containerizing the Spring Boot application. Recognizing this gap, I decided to write this short article.

Prerequisites

Before diving in, we must have the following:

  • A foundational understanding of Spring Boot and microservices architecture 
  • Familiarity with Docker containers
  • Docker Desktop installed on our machine 

Docker Desktop Setup

We can install Docker Desktop using this link. Installation is straightforward and includes steps that can be navigated efficiently, as illustrated in the accompanying screenshots. 

Installing Docker Desktop: Configuration


Installing Docker Desktop: Unpacking files screenshot


Installing Docker Desktop: Installation succeeded screenshot

Configuring MySQL Container

Once we have installed the Docker desktop when we launch, we will get through some standard questions, and we can skip the registration part. Once the desktop app is ready, then we need to search for the MySQL container, as shown below:

Search for the MySQL container

We need to click Pull and then Run the container. Once you run the container, the settings dialog will pop up, as shown below.

Run a new container: settings dialog screen

Please enter the settings as below:

Run a new container: fields to enter

  • MYSQL_ROOT_PASSWORD: This environment variable specifies the password that will be set for the MySQL root superuser account.
  • MYSQL_DATABASE: This environment variable allows us to specify the name of a database that will be created on image startup. If a user/password was supplied (see below), that user will be granted superuser access (corresponding to GRANT ALL) to this database.
  • MYSQL_USER, MYSQL_PASSWORD: These variables are used to create a new user and set that user's password. This user will be granted superuser permissions for the database specified by the MYSQL_DATABASE variable. 

Upon running the container, Docker Desktop displays logs indicating the container's status. 

Docker Desktop displaying logs indicating the container's status

We can now connect to the MySQL instance using tools like MySQL Workbench to manage database objects.

MySQL Connections: DOCKER-MYSQL Connection screen


MySQL Workbench: Query 1 screen


MySQL Workbench: eSign tables screen

Spring Application

Configuration

In the Spring application, we can configure the configurations below in the application.properties.

YAML
 
spring.esign.datasource.jdbc-url=jdbc:mysql://localhost:3306/e-sign?allowPublicKeyRetrieval=true&useSSL=false
spring.esign.datasource.username=e-sign
spring.esign.datasource.password=Password1


We opted for a custom prefix spring.esign over the default spring.datasource for our database configuration within the Spring Boot application. This approach shines in scenarios where the application requires connections to multiple databases. To enable this custom configuration, we need to define the Spring Boot configuration class ESignDbConfig:

Java
 
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "eSignEntityManagerFactory",
        transactionManagerRef = "eSignTransactionManager",
        basePackages ="com.icw.esign.repository")
public class ESignDbConfig {

    @Bean("eSignDataSource")
    @ConfigurationProperties(prefix="spring.esign.datasource")
    public DataSource geteSignDataSource(){
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    @Bean(name = "eSignEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean eSignEntityManagerFactory(
            EntityManagerFactoryBuilder builder, @Qualifier("eSignDataSource") DataSource dataSource) {
        return builder.dataSource(dataSource).packages("com.icw.esign.dao")
                .build();
    }

    @Bean(name = "eSignTransactionManager")
    public PlatformTransactionManager eSignTransactionManager(@Qualifier("eSignEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}


  • @Bean("eSignDataSource"): This method defines a Spring bean for the eSign module's data source. The @ConfigurationProperties(prefix="spring.esign.datasource") annotation is used to automatically map and bind all configuration properties starting with spring.esign.datasource from the application's configuration files (like application.properties or application.yml) to this DataSource object. The method uses DataSourceBuilder to create and configure a HikariDataSource, a highly performant JDBC connection pool. This implies that the eSign module will use a dedicated database whose connection parameters are isolated from other modules or the main application database.
  • @Bean(name = "eSignEntityManagerFactory"): This method creates a LocalContainerEntityManagerFactoryBean, which is responsible for creating the EntityManagerFactory. This factory is crucial for managing JPA entities specific to the eSign module. The EntityManagerFactory is configured to use the eSignDataSource for its database operations and to scan the package com.icw.esign.dao for entity classes. This means that only entities in this package or its subpackages will be managed by this EntityManagerFactory and thus, can access the eSign database.
  • @Bean(name = "eSignTransactionManager"): This defines a PlatformTransactionManager specific way of managing transactions of the eSignmodule's EntityManagerFactory. This transaction manager ensures that all database operations performed by entities managed by the eSignEntityManagerFactory are wrapped in transactions. It enables the application to manage transaction boundaries, roll back operations on failures, and commit changes when operations succeed.

Repository

Now that we have defined configurations, we can create repository classes and build other objects required for the API endpoint. 

Java
 
@Repository
public class ESignDbRepository {
    private static final Logger logger = LoggerFactory.getLogger(ESignDbRepository.class);
    @Qualifier("eSignEntityManagerFactory")
    @Autowired
    private EntityManager entityManager;

    @Autowired
    ObjectMapper objectMapper;

    String P_GET_DOC_ESIGN_INFO = "p_get_doc_esign_info";

    public List<DocESignMaster> getDocumentESignInfo(String docUUID) {
        StoredProcedureQuery proc = entityManager.createStoredProcedureQuery(P_GET_DOC_ESIGN_INFO, DocESignMaster.class);
        proc.registerStoredProcedureParameter("v_doc_uuid", String.class, ParameterMode.IN);
        proc.setParameter("v_doc_uuid", docUUID);
        try {
            return (List<DocESignMaster>) proc.getResultList();
        } catch (PersistenceException ex) {
            logger.error("Error while fetching document eSign info for docUUID: {}", docUUID, ex);
        }
        return Collections.emptyList();
    }
}


  • @Qualifier("eSignEntityManagerFactory"): Specifies which EntityManagerFactory should be used to create EntityManager, ensuring that the correct database configuration is used for eSign operations.

Conclusion

Integrating Spring Boot microservices with Docker Desktop streamlines microservice development and testing. This guide walks through the essential steps of setting up a Spring Boot application and ensuring seamless service communication with a MySQL container hosted on the Docker Desktop application. This quick setup guide is useful for proof of concept or setting up an isolated local development environment.

MySQL Docker (software) Spring Boot microservices Integration

Opinions expressed by DZone contributors are their own.

Related

  • Effective Exception Handling in Microservices Integration
  • Keep Your Application Secrets Secret
  • Smart Deployment Strategies for Modern Applications
  • Building Fault-Tolerant Spring Boot Microservices With Kafka and AWS

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook