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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Effective Exception Handling in Microservices Integration
  • Keep Your Application Secrets Secret
  • Running a Java App With MySQL in Any Docker Environment
  • Docker With Spring Boot and MySQL: Docker Swarm Part 3

Trending

  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer
  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples
  • How Kubernetes Cluster Sizing Affects Performance and Cost Efficiency in Cloud Deployments
  • Orchestrating Microservices with Dapr: A Unified Approach
  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
6.9K 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
  • Running a Java App With MySQL in Any Docker Environment
  • Docker With Spring Boot and MySQL: Docker Swarm Part 3

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!