Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Introduction to the method of connecting spring boot and mysql containers with docker

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

A small example of running Spring Boot was previously deployed using docker, but the database was not used. In this article, you'll see how docker starts the mysql container and how to connect the Spring Boot container to the mysql container to run.

Docker basic command

First, familiarize yourself with the basic docker commands that are commonly used during operation:

Docker images: list all docker images docker ps: list all running containers,-a parameter can list all containers, including stopped docker stop container_id: stop container docker start container_name: start stopped container docker rm container_id: delete stopped container, add-f option to force deletion of running container docker rmi image_id: delete image, provided that the image does not have a corresponding container docker running mysql container

First, create a new Dockerfile:

FROM ubuntu:14.04MAINTAINER loveqhRUN apt-get updateRUN apt-get-y install mysql-serverRUN / etc/init.d/mysql start\ & & mysql- uroot-e "grant all privileges on *. * to 'root'@'%' identified by' 123456;"\ & & mysql- uroot-e "grant all privileges on *. * to 'root'@'localhost' identified by' 123456' "RUN sed-Ei's / ^ (bind-address | log) / # & /'/ etc/mysql/my.cnf\ & & echo 'skip-host-cache\ nskip-name-resolve' | awk' {print} $1 =" [mysqld] "& & c = = 0 {c = 1; system (" cat ")}'/ etc/mysql/my.cnf > / tmp/my.cnf\ & mv / tmp/my.cnf / etc/mysql/my.cnfEXPOSE 3306 CMD [" / usr/bin/mysqld_safe "]

Then create a mysql image:

Docker build-t loveqh/mysql.

The next step is to start a container from the image:

Docker run-d-P-- name docker-mysql loveqh/mysql

Among them

-d means to run the container in the background and return the container id

-P maps all exposed ports of the container to the random port number of the host. You can also use-p to specify the mapping relationship of a container port, such as-p 33060, which maps port 3306 of the container to port 33060 of the host.

You can view the container port mapping through docker ps, which is shown in the PORTS column.

0.0.0.0VOVA 32770-> 3306/tcp

That is, mysql is mapped to port 32770 of the host, so you can use the

Mysql-h 0.0.0.0-P 32770-uroot-p

Connected to the mysql container.

Docker connects spring boot and mysql containers

In the previous article, an instance of Spring Boot was run in docker, but the database was not used. Next we add database operations on the basis of the project.

First, create a new application.properties file under resources to configure the database:

Spring.datasource.url = jdbc:mysql://localhost:3306/springspring.datasource.username = rootspring.datasource.password = 123456spring.datasource.driverClassName = com.mysql.cj.jdbc.Driver

Note: the url here will be modified later after connecting to the mysql container.

Create a new schema.sql file, which is automatically executed by Spring Boot when it starts, so you can create data tables and insert test data in the file:

Use spring;create table if NOT EXISTS user (id int PRIMARY KEY NOT NULL auto_increment, name VARCHAR (30), password VARCHAR (10), email VARCHAR (30));-- INSERT INTO user (name, password, email) values ("test", "001", "test@163.com") INSERT INTO user (name, password, email) SELECT * FROM (SELECT "test", "001", "test@163.com") AS tmpWHERE NOT EXISTS (SELECT name FROM user WHERE name='test' AND email='test@163.com') limit 1

In this file, you specify the database spring to be used, and then create a new one if there is no user table. Next, when you insert the test data, you comment on the simple insert command, because this will insert the same record every time you start the project, so use the following statement instead.

Follow the previous steps to create a Spring Boot image:

Docker build-t loveqh/spring-boot-mysql-docker.

The following is the connection to run the Spring Boot container and connect to the mysql database:

Docker run-d-p 8088 8080-name spring-web-link docker-mysql:mysql loveqh/spring-boot-mysql-docker

Among them

-d is still running in the background. If you don't want to run in the background, you can replace the-d parameter with-it, so you can see the output of the project. Of course, you can also view the container log through docker logs container-name/container-id.

The-p parameter maps the default port 8080 of Spring Boot in the container to port 8088 of the host.

-name specifies the name of the container so that it can be restarted via docker start spring-web after the container is stopped.

The-link parameter connects to the docker-mysql container and uses the alias mysql

At the beginning, we have been struggling with how the spring boot project configures mysql addresses, because there is no port mapping specified when running the mysql container, which is randomly mapped, and if we write localhost: map ports in the url of mysql, then we will not use link to connect the two containers. Finally, after reading some materials, I suddenly realized that after using-link, docker will bind the parent container (the mysql container here) to the ip address of the parent container in the / etc/hosts of the child container (spring boot container here), so we can mysql:3306 to access the database. That is, change the database url in application.properties to:

Spring.datasource.url = jdbc:mysql://mysql:3306/spring

The second mysql is the alias we set up earlier.

Then visit http://localhost:8088 and you can see the result of the run.

Project code

Because this article is mainly about docker connecting two containers, there is no description of the code, but the key code is simply pasted out below.

Index-Home name:password:email:

/ / UserController.javapackage com.xxx;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import java.util.List;/** * Created by wangl on 17-5-16. * / @ Controller@RequestMapping ("/ user") public class UserController {@ Autowired private UserDao userDao; @ RequestMapping (method = RequestMethod.GET) public String index (Model model) {model.addAttribute ("user", new User ()); return "index";} @ RequestMapping ("/ list") public String list (Model model) {Listusers = userDao.findAll (); model.addAttribute ("users", users); return "list" } @ RequestMapping (value = "/ registry", method = RequestMethod.POST) public String registry (@ ModelAttribute (value = "user") User user, Model model) {boolean flag = userDao.save (user); if (flag) {Listusers = userDao.findAll (); model.addAttribute ("users", users); return "list";} model.addAttribute ("info", "Registration failed!") ; return "fail";} / / UserDao.javapackage com.xxx;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.RowMapper;import org.springframework.stereotype.Repository;import java.util.List;/** * Created by wangl on 17-5-16. * / @ Repositorypublic class UserDao {@ Autowired private JdbcTemplate jdbcTemplate; public ListfindAll () {String sql = "select id, name, email from user"; RowMappermapper = (rs, rowNum)-> {User user = new User (); user.setId (rs.getLong (1)); user.setName (rs.getString (2)); user.setEmail (rs.getString (3)); return user;}; return jdbcTemplate.query (sql, mapper) } public boolean save (User user) {boolean exists = exists (user); if (exists) {return false;} String sql = "insert into user (name, password, email) values"; int count = jdbcTemplate.update (sql, user.getName (), user.getPassword (), user.getEmail ()); return count = = 1 } public boolean exists (User user) {String sql = "select count (*) from user where name=?"; int count = jdbcTemplate.queryForObject (sql, new Object [] {user.getName ()}, int.class); return count! = 0 }} list-user list id name email stat:index stat:count stat:size stat:current stat:even stat:odd stat:first stat:last id,error name,error email,error error

Problem record

In the process of doing encountered a lot of problems, after checking the data to solve, now record it.

Error encountered while using thymeleaf template engine: org.xml.sax.SAXParseException: The element type "THYMELEAF_ROOT" must be terminated by the matching end-tag

Encountered a lot of thymeleaf errors before, all of which are the closure of html tags. Check carefully whether the tags in the html file are closed and whether they correspond to each other.

When visiting the registration page of index, I encountered an error: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'user' available as request attribute

The thymeleaf auto-binding form is used for submission, and it takes a long time to check the registry method and index.html, and the result goes wrong no matter how you change it. Later, I found that there was th:object= "${user}" in the index page, but at first the index method did not add the object to the model, so there was an error that the user could not be obtained. The solution is to add a user object to model in all methods that return index:

Model.addAttribute ("user", new User ())

Summary

This is the whole content of this article about how docker connects spring boot and mysql containers. I hope it will be helpful to you. Interested friends can continue to refer to this site: talk about the network security between Docker security mechanism, kernel security and containers, explain in detail that Docker uses Linux iptables and Interfaces to manage container network, Windows uses docker to open new windows error solutions, etc. If you have any questions, you can leave a message at any time, and the editor will reply to you in time. Here are some books about learning docker for reference to docker enthusiasts:

The complete pdf scanned version of the bookmarked directory of the first Docker book

Https://www.jb51.net/books/514869.html

Docker Container and Container Cloud (2nd Edition) complete pdf scan version

Https://www.jb51.net/books/569549.html

I hope you like it!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report