Running a Java App With MySQL in Any Docker Environment
In this article, take a look at using Docker network to take advantage of container isolation features.
Join the DZone community and get the full member experience.Join For Free
We very often use a container for the deployment of a microservices application/java app. Using containers has various advantages, and Docker is one of the first choices to implement containerization. But for a beginner, using Docker with proper configuration is a tedious job, particularly if we use using a database as backends. Since containerization means isolation of any application to the external world, an application cannot access any of the services, which are running in a container.
An application needs any kind of backend service. So the backend needs to expose to the external world. But, exposing the port of the database for the external world, is not a good idea. But this problem can be solved by connecting the container through Docker networking. By connecting the database with the java application through the docker network is the best option. This way, we can solve the portability issues in different environments like Dev, QA, and Prod.
A Spring Boot application running with MySQL in Docker container with Docker network.
application.properties for Springboot application, where MySQL is running in Docker container in a network with name app_network.
# configure mysql database
The Spring Boot application can communicate to MySQL in Docker containers, through the docker network.
The name of Docker network is app_network:
docker network create app_network
Dockerfile file for Spring Boot is configured as follows.
CMD [“mkdir”, “app”]
COPY target/sampleApp.jar app/app.jar
CMD [“java”, “-jar”, “app/app.jar”]
Spring Boot application image name is sample_app.
docker build -t sample_app .
Running Spring Boot image in Docker with network app_network
docker run -d -it -p 8082:8080 --network app_network --name sample_app sample_app
MySQL is running in Docker as mysql_name with password "password" and database "database_name" as follows:
docker run -d -it --network app_network -e MYSQL_ROOT_PASSWORD=password -e MYSQL_DATABASE=database_name --name mysql_name mysql
Now Spring Boot application can be run in any Docker environment without any IP address conflict.
Opinions expressed by DZone contributors are their own.
File Upload Security and Malware Protection
Building a Robust Data Engineering Pipeline in the Streaming Media Industry: An Insider’s Perspective
Mastering Go-Templates in Ansible With Jinja2
Performance Comparison — Thread Pool vs. Virtual Threads (Project Loom) In Spring Boot Applications