Deploy Spring Boot and MySQL applications in Docker containers (2023)

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.


(Video) Docker Deployment |How to Deploy Your Spring Boot CRUD Project With MySQL Database in Docker

What you will learn:

  1. How to create a Spring Boot application.
  2. How to configure a MySQL server in a Docker container.
  3. How to configure a Spring Boot application inside another Docker container.
  4. 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 JPAIMySQL driver.then clicktriggerbutton to download the item. Unzip and open in your IDE.

wsrc/main/java/com.example.dockerdemoThe package creates a file namedUser unitsUse these fields: First Name, Last Name, Email, Password. Annotate this class with@thememake it a JPA theme i@Table(name = "User")Map it to the "users" table in the MySQL database.

then create a fileuser libraryInterfaces in the same package that extendJpa database.This interface will provide us with basic CRUD operationsUser units.

(Video) Dockerize Spring Boot Application with MySQL

Finally, create auser controllerannotation 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.ymlfile to define our MySQL service. This cookie enables us to manage several services more efficiently.

hedocker-compose.ymlThis file should be created in the root directory of your Spring Boot projectpom.xmlIt 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.ymlIn the root directory of your Spring Boot project and paste the following:

(Video) Deploy and Run Spring boot with MySQL application in Docker and Docker Compose

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:

  1. Download the MySQL 8.0 image from Docker Hub.
  2. Create a new MySQL server.
  3. Set the root password to "root".
  4. Create a new database named "testdb" with user named "user" and password "password".
  5. Make the MySQL server available on port 3306.
  6. 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 fileInclude 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:

  • useabir jdk: 11as the base image.
  • Add output jar filedockerdemo-0.0.1-SNAPSHOT.jarofhedirectory 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.

(Video) Docker - Dockerizing your Spring Boot Application | Java Techie

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.ymlAnd 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.
  • hedepends on depends onMake 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. heSPRING_DATASOURCE_URLPointing to the service "db" iSPRING_DATASOURCE_USERNAMEISPRING_DATASOURCE_PASSWORDProvide credentials to connect to the MySQL server.

Run with this setupCreate dockerAccording to the wishes of the terminalrun two services. The Spring Boot application will run onlocalhost:8080And 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.

(Video) 9. Docker: Deploy MySQL DB and Spring Boot App in separate Containers on user-defined network

common problem

  1. 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.
  2. How can I ensure my Spring Boot application can communicate with the MySQL container?
    In the file of the Spring Boot application, you need to setspring.source.urlPoints 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.
  3. 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.
  4. 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.
  5. 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


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? ›

The steps are described below:
  1. Clone/Download/Create Spring Boot Application. ...
  2. Create Dockerfile and Add this with Spring Boot Application. ...
  3. Create a Docker-Compose file and Add this with Spring Boot Application. ...
  4. Update the application. ...
  5. Build Project using Maven. ...
  6. Run command for Docker Compose. ...
  7. Explore.

How to deploy MySQL database on Docker? ›

  1. Step 1: Pull the Docker Image for MySQL. Begin by taking the appropriate Docker Image for MySQL. ...
  2. Step 2: Deploy and Start the MySQL Container. ...
  3. Step 3: Connect with the Docker MySQL Container.
Jan 7, 2022

How to connect Docker container with MySQL container? ›

Start MySQL
  1. Create the network. $ docker network create todo-app.
  2. Start a MySQL container and attach it to the network. ...
  3. To confirm you have the database up and running, connect to the database and verify that it connects. ...
  4. Exit the MySQL shell to return to the shell on your machine.

How to containerize a Spring Boot application using Docker? ›

how to dockerize a Spring Boot application
  1. Download the repository.
  2. Check the project.
  3. Check the application.
  4. Add configuration to dockerize the Spring Boot application.
  5. Generate a .jar file.
  6. Build a Spring Boot Docker image.
  7. Run the Spring Boot Docker image in a container.
Aug 26, 2022

How to deploy Spring Boot with MySQL? ›

  1. Deploy a Spring Boot Project to Heroku. The process for deploying a Spring Boot project to Heroku is similar to this guide. ...
  2. Install ClearDB MySQL Add-on. ...
  3. Export local MySQL database to SQL file. ...
  4. Import SQL File to Remote MySQL Server. ...
  5. Access MySQL Database in Spring Boot App.
Oct 29, 2021

How to install a MySQL client on container? ›

Connect to the MySQL docker container.
  1. Make sure to install the MySQL client package before connecting to MySQL server. apt-get install mysql-client.
  2. Within the container, start the MySQL client by running the command. docker exec -it [container_name] mysql -uroot -p.
  3. Provide root password when asked for.
Sep 23, 2020

Should you run MySQL in Docker? ›

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? ›

Create a Database Instance
  1. Open your Google Cloud account and click SQL in the left menu.
  2. Click Create Instance.
  3. Choose your database engine. ...
  4. Choose an Instance ID. ...
  5. Select a root password.
  6. Choose the region. ...
  7. Click Show configuration options to expand the configuration options.

How do I access the MySQL shell in a docker container? ›

How to Start MySQL in Docker Container
  1. Step 1: Pull MySQL Docker Image.
  2. Step 2: Docker Run Command.
  3. Step 3: Docker exec Command. Running SQL commands. Creating a New User.
  4. Conclusion.
May 3, 2023

What is the difference between Docker Swarm and Kubernetes? ›

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? ›

Deploy your app
  1. Build images.
  2. Run your image as a container.
  3. Use containers for development.
  4. Run tests.
  5. Configure CI/CD.
  6. Deploy your app.

Is Spring Boot good for Docker? ›

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? ›

  1. 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: ...
  2. Start the User, Site, Organization and MySql using docker-compose. ...
  3. Check the created images. ...
  4. Check the created containers. ...
  5. Check the logs.

Can we connect MySQL with spring boot? ›

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? ›

Deploy SpringBoot with MySQL to Kubernetes (Minikube) – Step by Step Tutorial
  1. Create the Deployment YAML for MySQL.
  2. Test the MySQL Deployment.
  3. Modify the Application Properties file.
  4. Create the Application YAML File.
  5. Deploy and Test the Application.
Feb 8, 2022

How do I create a REST API with Spring Boot using MySQL and JPA? ›

Build a REST API With Spring Boot and MySQL
  1. The database structure of the task table.
  2. Generate a new Spring Boot project.
  3. Start the Spring Boot application.
  4. Test task creation from Postman.
  5. Test tasks list retrieval from Postman.
  6. Test task update from Postman.
Nov 6, 2022

How to install MySQL client in Docker? ›

How To Install MySQL with Docker on Windows
  1. Installing Docker. If you don't already have Docker, you can download the installer from the Docker website. ...
  2. Get the Official MySQL Docker Image. ...
  3. Set the Master Password and Run. ...
  4. Create a Database and User (Optional) ...
  5. Connect to Your Docker MySQL Database.

How to connect to MySQL Docker from Python application? ›

Set Up mysql Inside Docker
  1. Access mysql from terminal. To access mysql inside your docker container, do the following. ...
  2. Create a database. Now, you are inside mysql as root user. ...
  3. Create a table inside the new database. Here, we will create a table so we can test our Python application later. ...
  4. Create a new user.
Mar 24, 2019

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? ›

If you're choosing a database for analysis purposes and you stumble across this post, read on and learn why MySQL is the wrong choice.
  1. No Window Functions. Window functions are one of the greatest tools in an analyst's tool belt. ...
  2. No Set-Returning Functions. ...
  3. No Strictness on Groupings. ...
  4. No JSON Support.

What are the benefits of Docker MySQL? ›

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.

Where to deploy MySQL database? ›

The following cloud providers offer managed MySQL databases that you can purchase, configure, and scale as your needs require:
  1. Amazon AWS.
  2. Google Cloud.
  3. Microsoft Azure.
  4. Oracle.
  5. DigitalOcean.
  6. Heroku.

Does MySQL require a server? ›

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? ›

Deploy a containerized app to Azure
  1. Create a container image for your application.
  2. Push the image to a container registry.
  3. Deploy the image to Azure App Service or Azure Container Apps.

How to deploy an API in docker? ›

  1. Step 1: Install docker. Download the docker installer from ...
  2. Step 2: Install python and flask.
  3. Step 3: Create flask API. ...
  4. Step 5: Generate requirements file. ...
  5. Step 6: Create dockerfile. ...
  6. Step 7: Build and run the docker image. ...
  7. Step 8: Push and pull Docker images (optional)
Aug 16, 2022

What is the difference between deploying applications on hosts and containers? ›

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? ›

  1. Step 1: Create a project file: Open command prompt (in folder where you want to start, our case using src as root folder ) ...
  2. Step 2: Create a Dockerfile : echo dockerfile>Dockerfile. ...
  3. Step 3: Create a Docker Compose: Navigate to Root folder and create docker-compose. ...
  4. Step 4: RUN the application:

Can Docker run multiple applications? ›

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? ›

Start MySQL
  1. Create the network by using this command. Bash Copy. ...
  2. Start a MySQL container and attach it the network. ...
  3. Get your container ID by using the docker ps command.
  4. To confirm you have the database up and running, connect to the database. ...
  5. In the MySQL shell, list the databases and verify you see the todos database.
Mar 9, 2023

How to connect the Tomcat container with MySQL container? ›

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.

How to connect MySQL with Spring Boot in Kubernetes? ›

Deploy SpringBoot with MySQL to Kubernetes (Minikube) – Step by Step Tutorial
  1. Create the Deployment YAML for MySQL.
  2. Test the MySQL Deployment.
  3. Modify the Application Properties file.
  4. Create the Application YAML File.
  5. Deploy and Test the Application.
Feb 8, 2022

How to connect to MongoDB container? ›

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? ›

To pull and run the Docker container images for SQL Server, follow the prerequisites and steps in the following quickstart:
  1. Run the SQL Server 2017 container image with Docker.
  2. Run the SQL Server 2019 container image with Docker.
  3. Run the SQL Server 2022 container image with Docker.
Mar 30, 2023

How to deploy multi containerized application using docker compose? ›

Next steps
  1. Create an Azure container registry.
  2. Clone application source code from GitHub.
  3. Use Docker Compose to build an image and run a multi-container application locally.
  4. Push the application image to your container registry.
  5. Create an Azure context for Docker.
  6. Bring up the application in Azure Container Instances.
Jan 11, 2023

What is the difference between Tomcat container and docker container? ›

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? ›

In this guide, we'll walk you through how to install MySQL in your Docker container on Windows.
  1. Installing Docker. ...
  2. Get the Official MySQL Docker Image. ...
  3. Set the Master Password and Run. ...
  4. Create a Database and User (Optional) ...
  5. Connect to Your Docker MySQL Database.

How to install MySQL connector in Tomcat? ›

Step to configure MYSQL with apache tomcat
  1. Copy mysql connection jar file to catalina_home lib directory.
  2. 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.
Aug 6, 2021

How do I run a MySQL container in Kubernetes? ›

  1. MySQL Deployment on Kubernetes. Step 1: Create Kubernetes Secret. Step 2: Create Persistent Volume and Volume Claim. Step 3: Create MySQL Deployment.
  2. Access Your MySQL Instance.
  3. Update Your MySQL Deployment.
  4. Delete Your MySQL Instance.
Sep 9, 2021

How to connect to MongoDB database in Docker container? ›

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? ›

To install it:
  1. Download and install the MongoDB image from Docker Hub: sudo docker pull mongo. ...
  2. Ensure the image has been installed: sudo docker images. ...
  3. 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.
Aug 27, 2021

How to connect MongoDB container to Spring Boot? ›

Spring Boot Application with MongoDB in Docker Container
  1. Overview. Docker Basics.
  2. Step 1: Creating a Basic Spring Boot Application. Maven Dependencies. Model Class. ...
  3. Step 2: Creating a Docker file.
  4. Step 3: Building a Docker image.
  5. Step 4: Running the MongoDB Container.
  6. Step 5: Running the Spring Application Container.
  7. Conclusion.
May 3, 2023


1. Deploy and Run Spring Boot + MYSQL Application to Docker
2. Episode 05: Connecting MySQL and Spring boot docker container
3. How to Run/Deploy Spring Boot & MySQL in Docker? | Tech Primers
(Tech Primers)
4. Spring Boot with MySQL Docker deployment using DOCKER COMPOSE
(Techies on-the-go)
(Layman's TechWorld)
6. docker compose example | spring boot & mysql docker-compose
(Coding Boot)
Top Articles
Latest Posts
Article information

Author: Msgr. Refugio Daniel

Last Updated: 03/07/2023

Views: 5783

Rating: 4.3 / 5 (54 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Msgr. Refugio Daniel

Birthday: 1999-09-15

Address: 8416 Beatty Center, Derekfort, VA 72092-0500

Phone: +6838967160603

Job: Mining Executive

Hobby: Woodworking, Knitting, Fishing, Coffee roasting, Kayaking, Horseback riding, Kite flying

Introduction: My name is Msgr. Refugio Daniel, I am a fine, precious, encouraging, calm, glamorous, vivacious, friendly person who loves writing and wants to share my knowledge and understanding with you.