[TOC]

Preface

Before we use docker deployed springboot , redis , mysql project, but is deployed in three different containers, need to first know redis and mysql of ip address manually configured to springboot application container, I just want to quickly locally The cost of testing is too high. Is there any way to centrally manage them? For example, build it into a mirror image.

There is always a way, that is Docker Compose .

Previous project address: https://github.com/Damaer/DemoCode/tree/main/springboot/springDocker

Previous: http://aphysia.cn/archives/ru-he-ji-yu-dockerkuai-su-da-jian-springbootmysqlredisxiang-mu-

Docker Compose

1. What is Docker Compose?

Docker Compose Docker tool used to define and run complex applications. What is a complex application, such as springboot + redis + mysql written earlier, there are three containers in it. For such multiple containers, use one tool to manage it. Fragrant?

Docker compose manages multiple Docker containers through a configuration file. In the configuration file, all containers service , and then use the docker-compose script to start, stop, and restart the application, as well as the services in the application and the containers it depends on.

2. The specific steps of Docker Compose

There are generally three steps:

  • Use Dockerfile to define the environment of the application
  • Define the services that make up the application in docker-compose.yml so that they can run together in an isolated environment.
  • Execute the docker-compose up command to start and run the entire application.

I am using Mac OS , installed Docker time has put Docker Compose also installed, you do not need to be installed separately.

3. How to use Docker Compose in IDEA projects

First pom.xml documents need to pay attention to configure lowercase artifactId :

    <groupId>com.aphysia</groupId>
    <artifactId>dockerdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>dockerdemo</name>
    <packaging>jar</packaging>

In addition, you need to configure the plug-in:

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>com.spotify</groupId>
                <artifactId>docker-maven-plugin</artifactId>
                <version>1.0.0</version>
                <!-- 将插件绑定在某个phase执行 -->
                <executions>
                    <execution>
                        <id>build-image</id>
                        <!-- 用户只需执行mvn package ,就会自动执行mvn docker:build -->
                        <phase>package</phase>
                        <goals>
                            <goal>build</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <imageName>${docker.image.prefix}/${project.artifactId}</imageName>
                    <dockerDirectory>src/main/docker</dockerDirectory>
                    <resources>
                        <resource>
                            <targetPath>/</targetPath>
                            <directory>${project.build.directory}</directory>
                            <include>${project.build.finalName}.jar</include>
                        </resource>
                    </resources>
                </configuration>
            </plugin>
        </plugins>
    </build>

In addition, Dockerfile is necessary, above the plug-in has been configured we dockerFile needs to be placed <dockerDirectory>src/main/docker</dockerDirectory> this position, DockerFile which configuration is as follows:

FROM openjdk:8-jdk-alpine
EXPOSE 8081
VOLUME /tmp
# 重写命名为app.jar
ADD dockerdemo-0.0.1-SNAPSHOT.jar app.jar
ENTRYPOINT ["java","-jar","/app.jar"]

In theory, by this time, we use mvn clean package to generate the corresponding jar package:

image-20211128215558740

docker compose most important thing for docker-compose.yml is to configure 061c4ab1c94fe7, this file can be placed in the root directory of the project, and it is the same as pom.xml :

version: "3"

services:
  redis:
    image: redis:latest
    restart: always
    ports:
      - "6389:6379"
    volumes:
      - /tmp/redis.conf:/etc/redis/redis.conf
    command: redis-server /etc/redis/redis.conf

  mysql:
    image: mysql:latest
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: "123456"
      MYSQL_USER: 'root'
      MYSQL_PASS: '123456'
    ports:
      - "3306:3306"
    volumes:
      - "./db:/var/lib/mysql"
      - "./conf/my.cnf:/etc/my.cnf"
      - "./init:/docker-entrypoint-initdb.d/"
  # 指定服务名称
  webapp:
    # 指定服务使用的镜像
    image: aphysia/dockerdemo
    # 指定容器名称
    container_name: dockerdemo
    # 指定服务运行的端口
    ports:
      - 8081:8081
    # 指定容器中需要挂载的文件
    volumes:
      - /etc/localtime:/etc/localtime
      - /tmp/dockerdemo/logs:/var/logs

Points worth noting:

  1. Service is the image we configured, including redis , mysql , webapp , webapp is actually our application.
  2. "6389:6379" in 6389 is actually the port of our host, that is, my Mac connection redis container needs to use 6389 , and the connection between containers needs to use 6379 , this is the container port.
  3. /tmp/redis.conf:/etc/redis/redis.conf in /tmp/redis.conf is the directory of the host, and this directory needs to be configured in docker, or it will report an error (remember to add administrator permissions to execute):

    docker ERROR: * start service *: Mounts denied

image-20211128220527229

  1. mysql 8.0 may report error java.sql.SQLNonTransientConnectionException: Public Key Retrieval is not allowed , this is because the url link is missing one parameter: allowPublicKeyRetrieval=true

Potential pits in startup

After startup, it may not be able to link to mysql or redis , but it is normal to see the container operation:

DockerCompose % docker container ps
CONTAINER ID   IMAGE                COMMAND                  CREATED          STATUS         PORTS                                                  NAMES
32fd6ce598ba   aphysia/dockerdemo   "java -jar /app.jar"     7 minutes ago    Up 7 minutes   0.0.0.0:8081->8081/tcp, :::8081->8081/tcp              dockerdemo
585b9b6bd71d   redis:latest         "docker-entrypoint.s…"   10 minutes ago   Up 7 minutes   0.0.0.0:6379->6379/tcp, :::6379->6379/tcp              dockercompose_redis_1
d96ba57941d9   mysql:latest         "docker-entrypoint.s…"   16 minutes ago   Up 7 minutes   0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp   dockercompose_mysql_1

docker-compose up no error when executing 061c4ab1c951d9, and an error is reported when requesting:

 io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: /127.0.0.1:6379

This is because the request can not be used between the container 127.0.0.1 , must mysql , redis behalf of the network of vessels, such as: jdbc:mysql://mysql:3306/test?characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true

The complete application.yml :

server:
  port: 8081
spring:
  #数据库连接配置
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://mysql:3306/test?characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true
    username: root
    password: 123456
  redis:
    host: redis     ## redis所在的服务器IP
    port: 6379
    ##密码,我这里没有设置,所以不填
    password:
    ## 设置最大连接数,0为无限
    pool:
      max-active: 8
      min-idle: 0
      max-idle: 8
      max-wait: -1
#mybatis的相关配置
mybatis:
  #mapper配置文件
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.aphysia.springdocker.model
  #开启驼峰命名
  configuration:
    map-underscore-to-camel-case: true
logging:
  level:
    root: debug

There is another problem, that is, the name of the mirror configured in docker-compose.yml docker-compose up executed, it will appear:

Pulling xxxx...
ERROR: The image for the service you're trying to recreate has been removed. If you continue, volume data could be lost. Consider backing up your data before continuing.

Continue with the new image? [yN]y
Pulling xxxx...
ERROR: pull access denied for postgresql, repository does not exist or may require 'docker login': denied: requested access to the resource is denied

I thought it was the reason for logging in. It was originally a local mirror. It should be create instead of pull . If you don’t know the name, you can check it with the following command, REPOSITORY is the name:

DockerCompose % docker images
REPOSITORY           TAG            IMAGE ID       CREATED             SIZE
aphysia/dockerdemo   latest         1429aa26790a   54 minutes ago      137MB
<none>               <none>         ceb493583d7c   57 minutes ago      137MB
<none>               <none>         dffcc47602a2   About an hour ago   137MB
<none>               <none>         a695cf2cd2df   About an hour ago   137MB
<none>               <none>         209ce4f96d34   2 hours ago         137MB
redis                latest         40c68ed3a4d2   10 days ago         113MB
mysql                latest         e1d7dc9731da   14 months ago       544MB
openjdk              8-jdk-alpine   a3562aa0b991   2 years ago         105MB

Finally start the command:

sudo docker-compose up

Successfully started:

image-20211128221753624

Remember to initialize the database data table after

drop database IF EXISTS test;
CREATE DATABASE test;
use test;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `name` varchar(255) DEFAULT "",
  `age` int(11) DEFAULT 0,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `user` VALUES (1, '李四', 11);
INSERT INTO `user` VALUES (2, '王五', 11);

image-20211128223429280

At this point, you're done, the seemingly simple command, in fact, there are still many holes.

[Profile of the author] :
Qin Huai, [161c4ab1c953c1 Qinhuai Grocery Store ], the road to technology is not at a time, the mountains are high and the rivers are long, even if it is slow, it will never stop. Personal writing direction: Java source code analysis, JDBC , Mybatis , Spring , redis , distributed, a series of articles that are distributed, 161c4ab1c953c9, I don’t like to write a series of articles, I don’t like to write LeetCode , I cannot guarantee that what I have written is completely correct, but I guarantee that what I have written has been practiced or searched for information. I hope to correct any omissions or errors.

refers to all offer solutions PDF

What did I write in 2020?

Open source programming notes


秦怀杂货店
147 声望38 粉丝

山高水长,纵使缓慢,驰而不息。