Step 1: Create a Docker Network
Create a Docker network to allow the containers to communicate with each other. You can create a network using the following command:
docker network create --subnet=172.18.0.0/16 mynetwork
This command creates a Docker network named "mynetwork" with a subnet of 172.18.0.0/16.
Step 2: Create a MySQL Container
Create a MySQL container using the following command:
docker run -d --name mysql-db --ip 172.18.0.2 --network mynetwork -e MYSQL_ROOT_PASSWORD=root mysql:latest
This command creates a MySQL container named "mysql-db" with an IP address of 172.18.0.2 and attaches it to the "mynetwork" network. It also sets the root password for the MySQL server.
Step 3: Create a Spring Boot Application
Create a Spring Boot application using your preferred IDE or text editor. You can use the Spring Initializr to generate a new Spring Boot project with the necessary dependencies.
Step 4: Configure Spring Boot Application
In your Spring Boot application, add the following configuration to your application.properties file:
spring.datasource.url=jdbc:mysql://mysql-db:3306/testdb
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
The above configuration sets the database URL, username, password, and driver class name for the MySQL server.
Step 5: Build and Run the Spring Boot Application
Build your Spring Boot application using Maven or Gradle. Then, run the application using the following command:
docker run -p 8080:8080 --name spring-app --network mynetwork <image-name>
This command runs your Spring Boot application in a Docker container named "spring-app" and maps port 8080 of the container to port 8080 of the host machine.
Note that you will need to replace with the name of the Docker image you built for your Spring Boot application.
Step 6: Test the Application
Open your web browser and navigate to http://localhost:8080. If everything is configured correctly, you should see your Spring Boot application running and connected to the MySQL container.
Top comments (0)