探索云原生技术之基石-Docker容器高级篇(3)

❤️作者简介:2022新星计划第三季云原生与云计算赛道Top5、华为云享专家、云原生领域潜力新星

博客首页:C站个人主页

作者目的:如有错误请指正,将来会不断的完善笔记,帮助更多的Java爱好者入门,共同进步!

文章目录

    • 探索云原生技术之基石-Docker容器高级篇(3)
      • Docker Compose 容器编排
        • 安装Docker Compose
        • 部署环境
          • 部署MySQL
          • 部署Redis
          • 打包微服务项目
        • 不使用Docker Compose编排容器(实战4)
          • 编写Dockerfile构建微服务项目镜像
        • 使用Docker Compose编排容器(实战4)
          • docker-compose config -q(检查docker-compose.yml的配置)
          • docker-compose up -d(一键''创建"docker-compose容器编排)
          • docker-compose stop(一键停止容器编排)
          • docker-compose start(一键启动容器编排)
          • docker-compose restart(一键重新启动容器编排)
          • docker-compose down(一键停止容器编排,并且删除之前编排的东西)
          • docker-compose常用命令
      • Docker轻量级工具portainer
        • 下载portainer
        • portainer页面
        • 使用portainer创建容器实例

探索云原生技术之基石-Docker容器高级篇(3)

本博文一共有7篇,如下

  • 探索云原生技术之基石-Docker容器入门篇(1)
  • 探索云原生技术之基石-Docker容器入门篇(2)
  • 探索云原生技术之基石-Docker容器入门篇(3)
  • 探索云原生技术之基石-Docker容器入门篇(4),=>由于篇幅过长,所以另起一篇

等你对Docker有一定理解的时候可以看高级篇,不过不太建议。

  • 探索云原生技术之基石-Docker容器高级篇(1)
  • 探索云原生技术之基石-Docker容器高级篇(2)
  • 探索云原生技术之基石-Docker容器高级篇(3)

剧透:未来将出云原生技术-Kubernetes(k8s),此时的你可以对Docker进行统一管理、动态扩缩容等等。

看完之后你会对Docker有一定的理解,并能熟练的使用Docker进行容器化开发、以及Docker部署微服务、Docker网络等等。干起来!

Docker Compose 容器编排

  • 按顺序一键启动N个容器实例或关闭N个实例,配置不同容器间的调用关系

安装Docker Compose

  • 1:拉取docker-compose
[root@aubin ~]# curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   664  100   664    0     0    563      0  0:00:01  0:00:01 --:--:--   564
100 12.1M  100 12.1M    0     0  1102k      0  0:00:11  0:00:11 --:--:-- 1538k
  • 2:给docker-compose分配权限:
chmod +x /usr/local/bin/docker-compose
  • 3:查看docker-compose的版本:
[root@aubin ~]# docker-compose --version
docker-compose version 1.29.2, build 5becea4c

部署环境

部署MySQL

关闭防火墙:

systemctl stop firewalld.service

启动MySQL:

docker run --restart always -d -p 3306:3306 --privileged=true -v /bf/mysql/log:/var/log/mysql -v /bf/mysql/data:/var/lib/mysql -v /bf/mysql/conf:/etc/mysql/conf.d -e MYSQL_ROOT_PASSWORD=123456 --name mysql mysql:5.7

创建my.cnf:

[root@aubin ~]# cd /bf/mysql/conf
[root@aubin conf]# vim my.cnf

my.cnf内容如下:

[client]
default_character_set=utf8
[mysqld]
collation_server=utf8_general_ci
character_set_server=utf8
docker restart mysql 
docker exec -it mysql /bin/bash
mysql -u root -p

输入密码:123456

创建数据库:

CREATE DATABASE compose_order;

使用数据库:

use compose_order;

数据库表:

CREATE TABLE `order` (
  `id` bigint(20) NOT NULL,
  `goodsInfo` varchar(255) NOT NULL,
  `goodsCount` int(20) NOT NULL,
  `singleGoodsMoney` decimal(10,2) NOT NULL,
  `phone` varchar(255) NOT NULL,
  `created` datetime DEFAULT NULL COMMENT '创建时间',
  `userid` bigint(20) NOT NULL,
   PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

插入数据:

INSERT INTO `order` VALUES(1001,'xxx1',3,100.0,'123456','2021-10-21 8:10:22',2);

INSERT INTO `order` VALUES(1002,'xxx2',4,200.0,'15456','2021-10-22 3:10:22',1);

INSERT INTO `order` VALUES(1003,'xxx3',5,300.0,'4516666','2021-10-23 5:10:22',3);

INSERT INTO `order` VALUES(1004,'xxx4',6,400.0,'155199','2021-10-23 6:10:22',5);

INSERT INTO `order` VALUES(1005,'xxx5',7,500.0,'6667588','2021-10-24 8:15:22',4);

INSERT INTO `order` VALUES(1006,'xxx6',8,600.0,'22699','2021-10-25 9:10:22',1);

INSERT INTO `order` VALUES(1007,'xxx7',9,700.0,'992266','2021-10-26 10:10:22',2);

INSERT INTO `order` VALUES(1008,'xxx8',10,800.0,'778899','2021-10-27 11:10:22',3);

INSERT INTO `order` VALUES(1009,'xxx9',11,900.0,'223311','2021-10-27 11:10:22',2);

INSERT INTO `order` VALUES(1010,'xxx10',12,1000.0,'6667788','2021-10-27 12:10:22',5);
部署Redis

启动Redis(测试环境

docker run --restart always -d --name redis -p 6379:6379 redis:latest redis-server
打包微服务项目

java代码,打包并上传到服务器上:(仅展示核心代码)

  • OrderMapper.class
package com.boot.dao;
import com.boot.pojo.Order;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface OrderMapper {
    @Insert("insert into `order`" +
            " values(#{id},#{goodsInfo},#{goodsCount},#{singleGoodsMoney},#{phone},#{created},#{userid})")
    int addOrder(Order order);
    @Select("select * from `order` where userid=#{userid}")
    List<Order> queryAllOrder(long userid);
    @Select("select * from `order` where id=#{orderId} and userid=#{userid}")
    Order queryOrderById(long orderId,long userid);
}
  • Order.class
package com.boot.pojo;
import io.swagger.annotations.ApiModel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.math.BigDecimal;
@ApiModel("订单类")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class Order implements Serializable {
    private long id;
    private String goodsInfo; //商品名
    private int goodsCount; //购买数量
    private BigDecimal singleGoodsMoney; //总价
    private String phone; //收货人电话
    private String created; //创建订单时间
    private long userid; //用户id
}
  • ResponseData.class
package com.boot.data;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class ResponseData<T> {
    private T msg;
    private int code;
}
  • OrderController.class
package com.boot.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.boot.data.ResponseData;
import com.boot.pojo.Order;
import com.boot.service.OrderService;
import com.boot.utils.SnowId;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;
@Controller
@RequestMapping(path = "/order")
@Slf4j
public class OrderController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderService orderService;
    private final String OD="od_oid_";
    private final String ODS="ods_uid_";
    private final int[] userIdArray ={1,2,3,4,5}; //定义用户id
    @ResponseBody
    @PostMapping(path = "/addOrder")
    public ResponseData<String> addOrder(Order order)
    {
        ResponseData<String> responseData = new ResponseData<>();
        LocalDateTime localDateTime = LocalDateTime.now();//获取当前时间
        String createTime = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Random random = new Random();
        order.setId(SnowId.nextId())
                .setGoodsInfo(order.getGoodsInfo())
                .setGoodsCount(order.getGoodsCount())
                .setSingleGoodsMoney(order.getSingleGoodsMoney())
                .setPhone(order.getPhone())
                .setCreated(createTime)
                .setUserid(userIdArray[random.nextInt(5)]);
        int rs = orderService.addOrder(order);
        if(rs==0){
            return responseData
                    .setMsg("添加订单失败")
                    .setCode(404);
        }else {
            return responseData
                    .setMsg("添加订单成功")
                    .setCode(200);
        }
    }
    @ResponseBody
    @GetMapping(path = "/queryAllOrder/{userid}")
    public ResponseData<List<Order>> queryAllOrder(@PathVariable("userid") long userid)
    {
        ResponseData<List<Order>> responseData = new ResponseData<>();
        try {
            String key=ODS+userid;
            String ods = (String) redisTemplate.opsForValue().get(key);
            if(StringUtils.isEmpty(ods)){ //如果缓存查不到,则从MySQL查询然后变成JSON再加入缓存
                List<Order> orders = orderService.queryAllOrder(userid);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("val",orders);
                redisTemplate.opsForValue().set(key,jsonObject.toJSONString());
                return responseData
                        .setMsg(orders)
                        .setCode(200);
            }else {
                JSONObject jsonObject = JSONObject.parseObject(ods);
                List<Order> orders = (List<Order>) jsonObject.get("val");
                return responseData
                        .setMsg(orders)
                        .setCode(200);
            }
        }catch (Exception ex){
            return responseData
                    .setMsg(null)
                    .setCode(200);
        }
    }
    @ResponseBody
    @GetMapping(path = "/queryOrderById/{orderid}/{userid}")
    public ResponseData<Order> queryOrderById(@PathVariable("orderid") long orderid,@PathVariable("userid") long userid)
    {
        ResponseData<Order> responseData = new ResponseData<>();
        try {
            String key=OD+orderid;
            String od = (String) redisTemplate.opsForValue().get(key);
            if(StringUtils.isEmpty(od)){
                Order order = orderService.queryOrderById(orderid,userid);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("val",order);
                redisTemplate.opsForValue().set(key,jsonObject.toJSONString());
                return responseData
                        .setMsg(order)
                        .setCode(200);
            }else {
                JSONObject jsonObject = JSONObject.parseObject(od);
                Order order = (Order) jsonObject.get("val");
                return responseData
                        .setMsg(order)
                        .setCode(200);
            }
        }catch (Exception ex){
            return responseData
                    .setMsg(null)
                    .setCode(200);
        }
    }
}
  • pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.5.9version>
        <relativePath/>
    parent>
    <groupId>org.examplegroupId>
    <artifactId>compose-javaartifactId>
    <version>1.0-SNAPSHOTversion>
    <properties>

        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
    properties>
    <dependencies>
        <dependency>
            <groupId>com.github.oshigroupId>
            <artifactId>oshi-coreartifactId>
            <version>5.8.2version>
        dependency>
        <dependency>
            <groupId>net.dreamlugroupId>
            <artifactId>mica-coreartifactId>
            <version>2.0.9-GAversion>
        dependency>
        <dependency>
            <groupId>net.dreamlugroupId>
            <artifactId>mica-xssartifactId>
            <version>2.0.9-GAversion>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.12version>
        dependency>
        <dependency>
            <groupId>com.github.yittergroupId>
            <artifactId>yitter-idgeneratorartifactId>
            <version>1.0.6version>
        dependency>
        <dependency>
            <groupId>org.springframework.sessiongroupId>
            <artifactId>spring-session-data-redisartifactId>
            <version>2.5.0version>
        dependency>
        <dependency>
            <groupId>com.squareup.okhttp3groupId>
            <artifactId>okhttpartifactId>
            <version>3.14.1version>
        dependency>
        <dependency>
            <groupId>io.jsonwebtokengroupId>
            <artifactId>jjwt-apiartifactId>
            <version>0.10.7version>
        dependency>
        <dependency>
            <groupId>io.jsonwebtokengroupId>
            <artifactId>jjwt-implartifactId>
            <version>0.10.7version>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>io.jsonwebtokengroupId>
            <artifactId>jjwt-jacksonartifactId>
            <version>0.10.7version>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>cn.hutoolgroupId>
            <artifactId>hutool-allartifactId>
            <version>5.5.2version>
        dependency>
        <dependency>
            <groupId>com.github.whvcsegroupId>
            <artifactId>easy-captchaartifactId>
            <version>1.6.2version>
        dependency>
        <dependency>
            <groupId>com.google.guavagroupId>
            <artifactId>guavaartifactId>
            <version>23.0version>
        dependency>
        <dependency>
            <groupId>org.apache.httpcomponentsgroupId>
            <artifactId>httpclientartifactId>
            <version>4.5.6version>
        dependency>
        <dependency>
            <groupId>org.jsoupgroupId>
            <artifactId>jsoupartifactId>
            <version>1.11.3version>
        dependency>
        <dependency>
            <groupId>eu.bitwalkergroupId>
            <artifactId>UserAgentUtilsartifactId>
            <version>1.20version>
        dependency>
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger2artifactId>
            <version>2.9.2version>
        dependency>
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger-uiartifactId>
            <version>2.9.2version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.2.6version>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.2.1version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-redisartifactId>
        dependency>
        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-lang3artifactId>
            <version>3.5version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.75version>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
    dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <version>2.5.9version>
                <configuration>
                    <mainClass>com.boot.ComposeApplicationmainClass>
                configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackagegoal>
                        goals>
                    execution>
                executions>
            plugin>
        plugins>
    build>
project>
  • 最后使用maven打包通过xftp上传centos服务器即可。

不使用Docker Compose编排容器(实战4)

编写Dockerfile构建微服务项目镜像

编写Dockerfile:

vim Dockerfile

内容如下:

FROM java:8
MAINTAINER youzhengjie<[email protected]>
VOLUME /tmp
ADD compose-java-1.0-SNAPSHOT.jar compose-java.jar
ENTRYPOINT ["java","-jar","compose-java.jar"]
EXPOSE 7200
  • 开始构建项目镜像:
docker build -t compose-java:1.6 .

构建结果如下:

[root@aubin m2]# docker build -t compose-java:1.6 .
Sending build context to Docker daemon   57.9MB
Step 1/6 : FROM java:8
 ---> d23bdf5b1b1b
Step 2/6 : MAINTAINER youzhengjie<1550324080@qq.com>
 ---> Using cache
 ---> d3a68015534b
Step 3/6 : VOLUME /tmp
 ---> Using cache
 ---> fdac864986c8
Step 4/6 : ADD compose-java-1.0-SNAPSHOT.jar compose-java.jar
 ---> f978ecfd98d2
Step 5/6 : ENTRYPOINT ["java","-jar","compose-java.jar"]
 ---> Running in 30872c1e917a
Removing intermediate container 30872c1e917a
 ---> cf503d6192ae
Step 6/6 : EXPOSE 7200
 ---> Running in 2086e29b0f93
Removing intermediate container 2086e29b0f93
 ---> 1fc5a5077e3a
Successfully built 1fc5a5077e3a
Successfully tagged compose-java:1.6
  • 运行项目镜像:
docker run -it -p 8899:7200 --name comp compose-java:1.6
  • 启动成功:
[root@aubin m2]# docker run -it -p 8899:7200 --name comp compose-java:1.6

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.5.9)

2022-05-17 06:58:01.941  INFO 1 --- [           main] com.boot.ComposeApplication              : Starting ComposeApplication v1.0-SNAPSHOT using Java 1.8.0_111 on 53be02223bb7 with PID 1 (/compose-java.jar started by root in /)
2022-05-17 06:58:01.967  INFO 1 --- [           main] com.boot.ComposeApplication              : No active profile set, falling back to default profiles: default
2022-05-17 06:58:03.147  INFO 1 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2022-05-17 06:58:03.152  INFO 1 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Redis repositories in DEFAULT mode.
2022-05-17 06:58:03.181  INFO 1 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 8 ms. Found 0 Redis repository interfaces.
2022-05-17 06:58:04.024  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 7200 (http)
2022-05-17 06:58:04.039  INFO 1 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-05-17 06:58:04.040  INFO 1 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.56]
2022-05-17 06:58:04.131  INFO 1 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-05-17 06:58:04.131  INFO 1 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2065 ms
2022-05-17 06:58:05.424  INFO 1 --- [           main] pertySourcedRequestMappingHandlerMapping : Mapped URL path [/v2/api-docs] onto method [springfox.documentation.swagger2.web.Swagger2Controller#getDocumentation(String, HttpServletRequest)]
2022-05-17 06:58:06.205  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 7200 (http) with context path ''
2022-05-17 06:58:06.206  INFO 1 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
2022-05-17 06:58:06.231  INFO 1 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
2022-05-17 06:58:06.262  INFO 1 --- [           main] s.d.s.w.s.ApiListingReferenceScanner     : Scanning for api listing references
2022-05-17 06:58:07.057  INFO 1 --- [           main] s.a.ScheduledAnnotationBeanPostProcessor : No TaskScheduler/ScheduledExecutorService bean found for scheduled processing
2022-05-17 06:58:07.068  INFO 1 --- [           main] com.boot.ComposeApplication              : Started ComposeApplication in 5.792 seconds (JVM running for 6.344)
  • 访问一下:
#测试下面的queryAllOrder接口:成功
192.168.184.132:8899/order/queryAllOrder/2

这就是不使用Docker Compose编排容器。

使用Docker Compose编排容器(实战4)

编写docker-compose.yml

vim docker-compose.yml
  • 内容如下:
#版本
version: "3"

# 指定服务列表
services:
  #指定服务名
  microService01:
  #指定容器的镜像
    image: compose-java:1.6
  #指定生成的容器名(若不指定则会使用默认)
    container_name: mservice01
  #端口映射,格式是(宿主机端口:容器端口)=>这里是外部网络访问8877相当于访问容器的7200。
    ports:
      - "8877:7200"
  #容器数据卷
    volumes:
      - /userdir/microService:/data
  #指定网络为我们自定义的网络,方便可以通过容器名去调用,而不是指定IP才能调用
    networks:
      - youzj_network
  #设置依赖关系。意思是在启动这个microService01之前会启动redis01和mysql01服务。
    depends_on:
      - redis01
      - mysql01

  redis01:
    image: redis:latest
    ports:
      - "6379:6379"
    volumes:
      - /home/redis/redis.conf:/usr/local/etc/redis/redis.conf
      - /home/redis/data:/data
    networks:
      - youzj_network
    command: redis-server /usr/local/etc/redis/redis.conf

  mysql01:
    image: mysql:5.7
    environment:
    # 设置root用户的密码:123456
      MYSQL_ROOT_PASSWORD: '123456'
    # 是否允许空密码:不允许
      MYSQL_ALLOW_EMPTY_PASSWORD: 'no'
      
      MYSQL_USER: 'admin'
      MYSQL_PASSWORD: '123456'
    ports:
      - "3306:3306"
    volumes:
      - /bf/mysql/data:/var/lib/mysql
      - /bf/mysql/conf:/etc/mysql/conf.d
      - /bf/mysql/init:/docker-entrypoint-initdb.d
      - /bf/mysql/log:/var/log/mysql
    networks:
      - youzj_network
    command: --default-authentication-plugin=mysql_native_password
# 创建自定义网络
networks:
  youzj_network:
docker-compose config -q(检查docker-compose.yml的配置)
docker-compose config -q
  • 执行上面的命令后,如果无输出结果=配置正常。
docker-compose up -d(一键’'创建"docker-compose容器编排)
  • docker-compose up和docker-compose start的区别:
    • up是创建容器实例并启动(相当于up是start的强化版)
    • start仅仅是启动,要建立在up之后的基础上才能执行。
[root@aubin m3]# docker-compose up -d
Creating network "m3_youzj_network" with the default driver
Creating m3_redis01_1 ... done
Creating m3_mysql01_1 ... done
Creating mservice01   ... done

查看一下docker实例

[root@aubin m3]# docker ps
CONTAINER ID   IMAGE              COMMAND                  CREATED          STATUS          PORTS                                                  NAMES
96a4e1857d81   compose-java:1.6   "java -jar compose-j…"   15 seconds ago   Up 14 seconds   0.0.0.0:8877->7200/tcp, :::8877->7200/tcp              mservice01
f5222efca7bb   redis:latest       "docker-entrypoint.s…"   15 seconds ago   Up 14 seconds   0.0.0.0:6379->6379/tcp, :::6379->6379/tcp              m3_redis01_1
78706bda824e   mysql:5.7          "docker-entrypoint.s…"   15 seconds ago   Up 14 seconds   0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp   m3_mysql01_1

访问一下接口:

#测试下面的queryAllOrder接口:成功
[root@aubin m3]# curl 192.168.184.132:8877/order/queryAllOrder/2
{"msg":[{"goodsCount":3,"singleGoodsMoney":100.00,"phone":"123456","created":"2021-10-21 08:10:22","id":1001,"userid":2,"goodsInfo":"xxx1"},{"goodsCount":9,"singleGoodsMoney":700.00,"phone":"992266","created":"2021-10-26 10:10:22","id":1007,"userid":2,"goodsInfo":"xxx7"},{"goodsCount":11,"singleGoodsMoney":900.00,"phone":"223311","created":"2021-10-27 11:10:22","id":1009,"userid":2,"goodsInfo":"xxx9"}],"code":200}
docker-compose stop(一键停止容器编排)
[root@aubin m3]# docker-compose stop
Stopping mservice01   ... done
Stopping m3_mysql01_1 ... done
Stopping m3_redis01_1 ... done

查看docker实例:全都是exited

[root@aubin m3]# docker ps -a
CONTAINER ID   IMAGE              COMMAND                  CREATED              STATUS                       PORTS     NAMES
96a4e1857d81   compose-java:1.6   "java -jar compose-j…"   About a minute ago   Exited (143) 7 seconds ago             mservice01
f5222efca7bb   redis:latest       "docker-entrypoint.s…"   About a minute ago   Exited (0) 7 seconds ago               m3_redis01_1
78706bda824e   mysql:5.7          "docker-entrypoint.s…"   About a minute ago   Exited (0) 5 seconds ago               m3_mysql01_1

这个时候去访问刚刚的接口:失败了

[root@aubin m3]# curl 192.168.184.132:8877/order/queryAllOrder/2
curl: (7) Failed connect to 192.168.184.132:8877; Connection refused
docker-compose start(一键启动容器编排)
[root@aubin m3]# docker-compose start
Starting redis01        ... done
Starting mysql01        ... done
Starting microService01 ... done

再次访问:又有了

[root@aubin m3]# curl 192.168.184.132:8877/order/queryAllOrder/2
{"msg":[{"goodsCount":3,"singleGoodsMoney":100.00,"phone":"123456","created":"2021-10-21 08:10:22","id":1001,"userid":2,"goodsInfo":"xxx1"},{"goodsCount":9,"singleGoodsMoney":700.00,"phone":"992266","created":"2021-10-26 10:10:22","id":1007,"userid":2,"goodsInfo":"xxx7"},{"goodsCount":11,"singleGoodsMoney":900.00,"phone":"223311","created":"2021-10-27 11:10:22","id":1009,"userid":2,"goodsInfo":"xxx9"}],"code":200}
docker-compose restart(一键重新启动容器编排)
[root@aubin m3]# docker-compose restart
Restarting mservice01   ... done
Restarting m3_mysql01_1 ... done
Restarting m3_redis01_1 ... done
docker-compose down(一键停止容器编排,并且删除之前编排的东西)
[root@aubin m3]# docker-compose down
Stopping mservice01   ... done
Stopping m3_mysql01_1 ... done
Stopping m3_redis01_1 ... done
Removing mservice01   ... done
Removing m3_mysql01_1 ... done
Removing m3_redis01_1 ... done
Removing network m3_youzj_network
  • docker-compose down是docker-compose up的相反。
  • docker-compose down和docker-compose stop是不一样的:
    • docker-compose stop仅仅是停止容器编排;
    • 而docker-compose down不仅仅会停止容器编排,而且会删除之前编排过的所有东西,相当于up创建的东西在这一刻全都没了,而stop不会。
  • 最显而易见的是:docker-compose stop之后可以重新执行start命令恢复回来,但是docker-compose down之后执行start命令会报错,无法恢复回来。
[root@aubin m3]# docker-compose start
Starting redis01        ... failed
Starting mysql01        ... failed
Starting microService01 ... failed
ERROR: No containers to start
ERROR: 1

查看docker实例

[root@aubin m3]# docker ps -a
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
  • 可以看出,docker-compose down直接把exited的容器都给删除了,而stop还把exited的容器保留着,这就是down和stop的区别。
docker-compose常用命令
docker-compose -h      #查看帮助文档
docker-compose up 	   #前台启动
docker-compose up -d   #后台启动
docker-compose down
docker-compose exec +服务id 
docker-compose ps 
docker-compose top 
docker-compose logs + 服务id
docker-compose config 
docker-compose config-q
docker-compose restart 
docker-compose start 
docker-compose stop 

Docker轻量级工具portainer

下载portainer

  • Https:
docker run -d -p 8000:8000 -p 9443:9443 --name portainer \
    --restart=always \
    -v /var/run/docker.sock:/var/run/docker.sock \
    -v portainer_data:/data \
    portainer/portainer-ce:2.11.0
  • Http:(我执行的是这个)
docker run -d -p 8000:8000 -p 9000:9000 --name portainer \
    --restart=always \
    -v /var/run/docker.sock:/var/run/docker.sock \
    -v portainer_data:/data \
    portainer/portainer-ce:2.11.0
  • 获取ip
[root@aubin ~]# ifconfig
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.184.132  netmask 255.255.255.0  broadcast 192.168.184.255
        inet6 fe80::5c87:5037:8d1d:7650  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:23:28:59  txqueuelen 1000  (Ethernet)
        RX packets 276481  bytes 371420079 (354.2 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 44045  bytes 6188169 (5.9 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
  • 通过ip+9000访问portainer==>192.168.184.132:9000

  • 第一次登录需要设置密码。

  • 本质上docker portainer就是使用到这些命令,例如:

[root@aubin ~]# docker system df
TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE
Images          11        2         1.967GB   1.694GB (86%)
Containers      3         3         0B        0B
Local Volumes   6         1         75.71MB   75.65MB (99%)
Build Cache     0         0         0B        0B

portainer页面

探索云原生技术之基石-Docker容器高级篇(3)_第1张图片
探索云原生技术之基石-Docker容器高级篇(3)_第2张图片
探索云原生技术之基石-Docker容器高级篇(3)_第3张图片
探索云原生技术之基石-Docker容器高级篇(3)_第4张图片探索云原生技术之基石-Docker容器高级篇(3)_第5张图片

使用portainer创建容器实例

探索云原生技术之基石-Docker容器高级篇(3)_第6张图片
探索云原生技术之基石-Docker容器高级篇(3)_第7张图片

❤️本章结束,下一章kubernates见❤️

你可能感兴趣的:(Java成神之路,探索云原生,云原生,容器,docker,微服务,java)