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.
Join the DZone community and get the full member experience.
Join For FreeDocker 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.
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:
We need to click Pull and then Run the container. Once you run the container, the settings dialog will pop up, as shown below.
Please enter the settings as below:
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 toGRANT 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 theMYSQL_DATABASE
variable.
Upon running the container, Docker Desktop displays logs indicating the container's status.
We can now connect to the MySQL instance using tools like MySQL Workbench to manage database objects.
Spring Application
Configuration
In the Spring application, we can configure the configurations below in the application.properties.
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
:
@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 withspring.esign.datasource
from the application's configuration files (likeapplication.properties
orapplication.yml
) to thisDataSource
object. The method usesDataSourceBuilder
to create and configure aHikariDataSource
, 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 aLocalContainerEntityManagerFactoryBean
, which is responsible for creating theEntityManagerFactory
. This factory is crucial for managing JPA entities specific to the eSign module. TheEntityManagerFactory
is configured to use theeSignDataSource
for its database operations and to scan the packagecom.icw.esign.dao
for entity classes. This means that only entities in this package or its subpackages will be managed by thisEntityManagerFactory
and thus, can access the eSign database.@Bean(name = "eSignTransactionManager")
: This defines aPlatformTransactionManager
specific way of managing transactions of theeSign
module'sEntityManagerFactory
. This transaction manager ensures that all database operations performed by entities managed by theeSignEntityManagerFactory
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.
@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 whichEntityManagerFactory
should be used to createEntityManager
, ensuring that the correct database configuration is used foreSign
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.
Opinions expressed by DZone contributors are their own.
Comments