In this tutorial, you will learn how to deploy a Spring Boot application and MySQL server in separate Docker containers. By the end of this tutorial, you'll know how to run a Spring Boot application in one Docker container, a MySQL server in another, and how to make them communicate with each other.
For more information on Docker, see otherDocker Tutorial for Beginners.
content
What you will learn:
- How to create a Spring Boot application.
- How to configure a MySQL server in a Docker container.
- How to configure a Spring Boot application inside another Docker container.
- How to enable communication between two Docker containers.
Previous requirements:
Before starting, the following software must be installed on your computer:
- Java Development Kit (JDK)
- stevedore
- IntelliJ IDEA or any preferred IDE
Create our Spring Boot application
First, supposeCreate our Spring Boot application using Spring Initializr.Openspring initializerin your browser. For project metadata, use the following values:
- group:com.example
- Man-made production:docker demo
- Package:bottle
- Java:11
blamedepend on, choosespring net
,Spring Data JPA
IMySQL driver
.then clicktrigger
button to download the item. Unzip and open in your IDE.
wsrc/main/java/com.example.dockerdemo
The package creates a file namedUser units
Use these fields: First Name, Last Name, Email, Password. Annotate this class with@theme
make it a JPA theme i@Table(name = "User")
Map it to the "users" table in the MySQL database.
then create a fileuser library
Interfaces in the same package that extendJpa database
.This interface will provide us with basic CRUD operationsUser units
.
Finally, create auser controller
annotation class@RestController
.plus/user
POST API endpoint that accepts user data in JSON format and stores it in the databaseuser library
.
Set up a MySQL server in a Docker container
The second step is to set up our MySQL server in a Docker container. This usually requires a Dockerfile. However, we intend to take a more flexible approach, adocker-compose.yml
file to define our MySQL service. This cookie enables us to manage several services more efficiently.
hedocker-compose.yml
This file should be created in the root directory of your Spring Boot projectpom.xml
It is crucial to have a file because docker-compose runs in the context of this directory, also known as the project root.
Here's what you should do:
Create a new file calleddocker-compose.yml
In the root directory of your Spring Boot project and paste the following:
Version: "3.1" Service: Database: Image: mysql:8.0 Restart: Always Environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: testdb MYSQL_USER: User MYSQL_PASSWORD: Password Port: -3306:3306 Volumes: -db_data: /var/lib/mysqlvolumes: db_data: {}
This script will do several things. yes:
- Download the MySQL 8.0 image from Docker Hub.
- Create a new MySQL server.
- Set the root password to "root".
- Create a new database named "testdb" with user named "user" and password "password".
- Make the MySQL server available on port 3306.
- Save the data in a Docker volume called "db_data" to ensure that data is not lost when the container is stopped.
Set up a Spring Boot application in a Docker container
To package our Spring Boot application into a Docker container, we first need a Dockerfile. Create a new file calleddocker file
Include the following in the root of your project:
Z openjdk:11ADD target/dockerdemo-0.0.1-SNAPSHOT.jar dockerdemo.jarEXPOSE 8080ENTRYPOINT ["Java", "-jar", "dockerdemo.jar"]
This Dockerfile does the following:
- use
abir jdk: 11
as the base image. - Add output jar file
dockerdemo-0.0.1-SNAPSHOT.jar
ofhe
directory to the docker image and rename it todockerdemo.jar
. - Port 8080 is provided.
- Specify the command to run our Spring Boot application.
Before building our Docker image, we need to package our application into a jar file. Open a terminal at the root of your project and do the following:./mvnw clean package
.
Now we can build our docker image using:docker compile -t docker.
Enable communication between two Docker containers
We successfully set up our Spring Boot application and MySQL server in separate Docker containers. Now we have to make them talk to each other.
back todocker-compose.yml
And add another service to our Spring Boot application:
Version: "3.1" Service: Database: Image: mysql:8.0 Restart: Always Environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: testdb MYSQL_USER: User MYSQL_PASSWORD: Password Port: - 3306:3306 Volume: - db_data: /var/lib/mysql web: Image: dockerdemo build: context: . dockerfile: Dockerfile port: - 8080:8080 Depends on: - db environment: SPRING_DATASOURCE_URL: jdbc: mysql://db:3306/testdb SPRING_DATASOURCE_USERNAME: user SPRING_DATASOURCE_PASSWORD: password SPRING_JPA_HIBERNATE_DDL_AUTO: updatevolumes: d b_data: {}
This file performs the following functions:
- As we did in step 2, set up a MySQL database in a Docker container. The MySQL server is exposed on port 3306 and the data is kept in a Docker volume named "db_data".
- Set up a Spring Boot application in another Docker container. It creates a Docker image for a Spring Boot application using the Dockerfile in the current directory, then runs the application and exposes it on port 8080.
- he
depends on depends on
Make sure the "db" service (MySQL server) will start before the "web" service (Spring Boot application). - Set an environment variable for the "web" service to connect to the "db" service. he
SPRING_DATASOURCE_URL
Pointing to the service "db" iSPRING_DATASOURCE_USERNAME
ISPRING_DATASOURCE_PASSWORD
Provide credentials to connect to the MySQL server.
Run with this setupCreate docker
According to the wishes of the terminalrun two services. The Spring Boot application will run onlocalhost:8080
And you will be able to interact with the MySQL server running in a separate Docker container.
Congratulations! You have successfully deployed your Spring Boot application and MySQL server in separate Docker containers and allowed communication between them.
common problem
- Why use docker-compose?
compose dockeris a tool for defining and managing multi-container Docker applications. It allows you to define your infrastructure, including application services, networks, and volumes, in a single file (docker-compose.yml), making it easy to manage and update your entire application. - How can I ensure my Spring Boot application can communicate with the MySQL container?
In the application.properties file of the Spring Boot application, you need to setspring.source.url
Points to the properties of the MySQL container. In the context of Docker Compose, you can use the service name as the hostname, for example:jdbc:mysql://db:3306/testdb
. - How to handle data persistence with MySQL in a Docker container?
In the docker compose file you canDefine a volume to hold datafrom the MySQL container. This means that the data will be stored on the host and persist after stopping and restarting the container. - Can I debug a Spring Boot application running in a Docker container?
if you can. By providing a debug port in your Dockerfile and running your Spring Boot application in debug mode, you can connect your IDE to your application for debugging. - Can I extend my Spring Boot application with Docker?
Yes, with Docker Compose you canExtend your applicationSpecifies the number of "replicas" of the application service to run. Combined with a load balancer, this allows you to handle higher application traffic.
related articles:
- Docker Compose: Implementation of Spring Boot Microservices
- Docker for Beginners: An Introduction to Docker, Images, and…
- How to run MySQL in a Docker container
- Managing Docker Containers: A Beginner's Guide
- Securing Docker Containers: Best Practices for Beginners
- Introduction to Docker Swarm: Orchestrating and Scaling...
- Docker volumes and bind mounts: managing data in containers
- Run a Spring Boot application on Docker using a configuration file
- A Spring Boot application with MongoDB in a Docker container
- Docker and DevOps: How Docker integrates with CI/CD...
Energeticcontextually relevant posts
FAQs
Deploy Spring Boot and MySQL applications in Docker containers? ›
Dockerized MySQL works well in development and staging environments where you want to quickly bring up isolated database instances. It's much quicker and easier to start a database in Docker than to configure a conventional MySQL installation in a full virtual machine.
How to connect Spring Boot container to MySQL container? ›- Clone/Download/Create Spring Boot Application. ...
- Create Dockerfile and Add this with Spring Boot Application. ...
- Create a Docker-Compose file and Add this with Spring Boot Application. ...
- Update the application. ...
- Build Project using Maven. ...
- Run command for Docker Compose. ...
- Explore.
- Step 1: Pull the Docker Image for MySQL. Begin by taking the appropriate Docker Image for MySQL. ...
- Step 2: Deploy and Start the MySQL Container. ...
- Step 3: Connect with the Docker MySQL Container.
- Create the network. $ docker network create todo-app.
- Start a MySQL container and attach it to the network. ...
- To confirm you have the database up and running, connect to the database and verify that it connects. ...
- Exit the MySQL shell to return to the shell on your machine.
- Download the repository.
- Check the project.
- Check the application.
- Add configuration to dockerize the Spring Boot application.
- Generate a .jar file.
- Build a Spring Boot Docker image.
- Run the Spring Boot Docker image in a container.
- Deploy a Spring Boot Project to Heroku. The process for deploying a Spring Boot project to Heroku is similar to this guide. ...
- Install ClearDB MySQL Add-on. ...
- Export local MySQL database to SQL file. ...
- Import SQL File to Remote MySQL Server. ...
- Access MySQL Database in Spring Boot App.
- Make sure to install the MySQL client package before connecting to MySQL server. apt-get install mysql-client.
- Within the container, start the MySQL client by running the command. docker exec -it [container_name] mysql -uroot -p.
- Provide root password when asked for.
Dockerized MySQL works well in development and staging environments where you want to quickly bring up isolated database instances. It's much quicker and easier to start a database in Docker than to configure a conventional MySQL installation in a full virtual machine.
What port does Docker MySQL use? ›-p 3306:3306 maps host port 3306 to container port 3306, the port 3306 is MySQL's default port.
How to deploy MySQL database on cloud? ›- Open your Google Cloud account and click SQL in the left menu.
- Click Create Instance.
- Choose your database engine. ...
- Choose an Instance ID. ...
- Select a root password.
- Choose the region. ...
- Click Show configuration options to expand the configuration options.
How do I access the MySQL shell in a docker container? ›
- Step 1: Pull MySQL Docker Image.
- Step 2: Docker Run Command.
- Step 3: Docker exec Command. Running SQL commands. Creating a New User.
- Conclusion.
Docker Swarm is a lightweight, easy-to-use orchestration tool with limited offerings compared to Kubernetes. In contrast, Kubernetes is complex but powerful and provides self-healing, auto-scaling capabilities out of the box.
How do I deploy an application to a docker container? ›- Build images.
- Run your image as a container.
- Use containers for development.
- Run tests.
- Configure CI/CD.
- Deploy your app.
Why is containerizing a Spring Boot app important? Running your Spring Boot application in a Docker container has numerous benefits. First, Docker's friendly, CLI-based workflow lets developers build, share, and run containerized Spring applications for other developers of all skill levels.
How to deploy multiple Spring Boot microservices in Docker? ›- Create a JAR file for each service. Run maven command - clean install, and a jar file gets created in the target directory for each service like so: ...
- Start the User, Site, Organization and MySql using docker-compose. ...
- Check the created images. ...
- Check the created containers. ...
- Check the logs.
The following steps will help you in setting up the Spring Boot MySQL Integration: Step 1: Creating a MySQL Database. Step 2: Append MySQL Dependencies. Step 3: Set Spring Boot MySQL Connection Configuration.
How to deploy Spring Boot application with MySQL database in Kubernetes? ›- Create the Deployment YAML for MySQL.
- Test the MySQL Deployment.
- Modify the Application Properties file.
- Create the Application YAML File.
- Deploy and Test the Application.
- The database structure of the task table.
- Generate a new Spring Boot project.
- Start the Spring Boot application.
- Test task creation from Postman.
- Test tasks list retrieval from Postman.
- Test task update from Postman.
- Installing Docker. If you don't already have Docker, you can download the installer from the Docker website. ...
- Get the Official MySQL Docker Image. ...
- Set the Master Password and Run. ...
- Create a Database and User (Optional) ...
- Connect to Your Docker MySQL Database.
- Access mysql from terminal. To access mysql inside your docker container, do the following. ...
- Create a database. Now, you are inside mysql as root user. ...
- Create a table inside the new database. Here, we will create a table so we can test our Python application later. ...
- Create a new user.
Is it safe to run database in Docker container? ›
What About My Simple Live App? If you're working on a small project, and are deploying to a single machine, it's completely okay to run your database in a Docker container. Be sure to mount a volume to make the data persistent, and have backup processes in place.
Which is the best SQL database for Docker? ›We can compare database image size, initial memory usage in Docker and initial CPU usage. By these results, it looks like PostgreSQL is the winner, and SQL Server is the loser.
When should you not use MySQL? ›- No Window Functions. Window functions are one of the greatest tools in an analyst's tool belt. ...
- No Set-Returning Functions. ...
- No Strictness on Groupings. ...
- No JSON Support.
Docker makes it easy to consistently deploy and manage the MySQL database across different environments, such as development, testing, and production. This consistency helps ensure that the database is always configured in the same way and reduces the risk of errors or inconsistencies.
What is the best port for MySQL? ›If you want to connect directly to your MySQL database or connect another application to your database, you'll need to know the MySQL port, along with some other information. The default MySQL port is 3306, so you should be able to use “3306” as the port for most situations.
Which port is best for MySQL server? ›Port 3306 (TCP)
MySQL clients connect to the MySQL server through port 3306 by default. As a rule, the communication on this port is encrypted. Unless the X protocol is utilized, communication on this port must go in the direction from client to server.
- Amazon AWS.
- Google Cloud.
- Microsoft Azure.
- Oracle.
- DigitalOcean.
- Heroku.
The answer is yes, you do. MySQL Workbench is a powerful graphical tool for database design and administration. It is a great tool for managing and developing databases, but it requires a web server to be able to access the database. Without a web server, you won't be able to access the database from the Workbench.
Can MySQL be cloud based? ›Cloud SQL for MySQL is a fully-managed database service that helps you set up, maintain, manage, and administer your MySQL relational databases on Google Cloud Platform.
Is Docker Swarm obsolete? ›— Running a swarm cluster in production has proven to orchestrate workloads successfully. Is Docker Swarm becoming deprecated? — It is not being deprecated and is still a viable option for orchestrating multiple workloads.
Is Docker Swarm still viable? ›
Docker Swarm is not being deprecated, and is still a viable method for Docker multi-host orchestration, but Docker Swarm Mode (which uses the Swarmkit libraries under the hood) is the recommended way to begin a new Docker project where orchestration over multiple hosts is required.
Is Docker Swarm still popular? ›Kubernetes and Docker Swarm are the most popular container orchestration tools available today. These tools can be used to deploy and manage containers on your own infrastructure, but they also provide a way to run your own container services in the cloud.
How do you deploy a containerized application? ›- Create a container image for your application.
- Push the image to a container registry.
- Deploy the image to Azure App Service or Azure Container Apps.
- Step 1: Install docker. Download the docker installer from https://docs.docker.com/desktop. ...
- Step 2: Install python and flask.
- Step 3: Create flask API. ...
- Step 5: Generate requirements file. ...
- Step 6: Create dockerfile. ...
- Step 7: Build and run the docker image. ...
- Step 8: Push and pull Docker images (optional)
Deploying Applications consist of an architecture that has an operating system. The operating system will have a kernel that holds various libraries installed on the operating system needed for an application. Whereas container host refers to the system that runs the containerized processes.
When should you not use spring boot? ›When you have a large number of different web apps, it can make sense to let the knowledge on that part only in the production team. In that case, you would not use Spring boot. On the other end, if the hosting is externalized, Spring boot allows to give a full package.
When should you not use Docker? ›Docker is great for developing web applications, but if your end-product is a desktop application, then we would suggest you not to use Docker. As it doesn't provide the environment for running the software with a graphical interface, you would need to perform additional workarounds.
Which cloud platform is best for spring boot? ›AWS is the most popular cloud and AWS Elastic Beanstalk makes it easy to deploy a variety of applications to AWS. “Learn AWS — Deploy Java Spring Boot to AWS Elastic Beanstalk” is another amazing hands-on course on AWS to help you deploy Spring Boot applications to AWS.
How to deploy microservices in Docker container? ›- Step 1: Create a project file: Open command prompt (in folder where you want to start, our case using src as root folder ) ...
- Step 2: Create a Dockerfile : echo dockerfile>Dockerfile. ...
- Step 3: Create a Docker Compose: Navigate to Root folder and create docker-compose. ...
- Step 4: RUN the application:
It's ok to have multiple processes, but to get the most benefit out of Docker, avoid one container being responsible for multiple aspects of your overall application. You can connect multiple containers using user-defined networks and shared volumes.
Can we deploy microservices with Docker? ›
Docker is an excellent tool for managing and deploying microservices. Each microservice can be further broken down into processes running in separate Docker containers, which can be specified with Dockerfiles and Docker Compose configuration files.
How to connect MySQL container to application container? ›- Create the network by using this command. Bash Copy. ...
- Start a MySQL container and attach it the network. ...
- Get your container ID by using the docker ps command.
- To confirm you have the database up and running, connect to the database. ...
- In the MySQL shell, list the databases and verify you see the todos database.
Inter-container Connection
To communicate with another container, you can connect with it by using its hostname as indicated by its container name. For example, to connect to the MySQL server from the 'tomcat' container, set the database address as mysql:3306.
- Create the Deployment YAML for MySQL.
- Test the MySQL Deployment.
- Modify the Application Properties file.
- Create the Application YAML File.
- Deploy and Test the Application.
If your application is running inside a container itself, you can run MongoDB as part of the same Docker network as your application using --network . With this method, you will connect to MongoDB on mongodb://mongodb:27017 from the other containerized applications in the network.
How to connect to SQL Server from Docker container? ›- Run the SQL Server 2017 container image with Docker.
- Run the SQL Server 2019 container image with Docker.
- Run the SQL Server 2022 container image with Docker.
- Create an Azure container registry.
- Clone application source code from GitHub.
- Use Docker Compose to build an image and run a multi-container application locally.
- Push the application image to your container registry.
- Create an Azure context for Docker.
- Bring up the application in Azure Container Instances.
Apache Tomcat is a Java process that contains J2EE servlets and JavaServer Pages. A Docker container is an operating system (OS) construct that contains a usable OS (as close as it can get) seperate from the host OS (as seperate as it can).
How to connect to MySQL docker container from host Windows? ›- Installing Docker. ...
- Get the Official MySQL Docker Image. ...
- Set the Master Password and Run. ...
- Create a Database and User (Optional) ...
- Connect to Your Docker MySQL Database.
- Copy mysql connection jar file to catalina_home lib directory.
- Configure that database parameter in server.xml file, resource name resource type, java .sql .data source, driver class name = mysql.jdbc.driver , URL= jdbc:mysql://host name of the musql server>:3306/tomcat.
How do I run a MySQL container in Kubernetes? ›
- MySQL Deployment on Kubernetes. Step 1: Create Kubernetes Secret. Step 2: Create Persistent Volume and Volume Claim. Step 3: Create MySQL Deployment.
- Access Your MySQL Instance.
- Update Your MySQL Deployment.
- Delete Your MySQL Instance.
For connecting to your local MongoDB instance from a Container you must first allow to accept connections from the Docker bridge gateway. To do so, simply add the respective gateway IP in the MongoDB config file /etc/mongod. conf under bindIp in the network interface section.
How to install MongoDB in Docker container? ›- Download and install the MongoDB image from Docker Hub: sudo docker pull mongo. ...
- Ensure the image has been installed: sudo docker images. ...
- Create a container with the mongo image in detached mode so that it is still interactive on your system: sudo docker run --name mongo_example -d mongo.
- Overview. Docker Basics.
- Step 1: Creating a Basic Spring Boot Application. Maven Dependencies. Model Class. ...
- Step 2: Creating a Docker file.
- Step 3: Building a Docker image.
- Step 4: Running the MongoDB Container.
- Step 5: Running the Spring Application Container.
- Conclusion.