1、瘦身插件
更改springBoot打jar包的插件即可改为一下格式:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<layout>ZIP</layout>
<includes>
<include>
<groupId>non-exists</groupId>
<artifactId>non-exists</artifactId>
</include>
</includes>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<classifier>classes</classifier>
<attach>false</attach>
</configuration>
</execution>
</executions>
</plugin>
如图:
2、生成lib目录
2、那么导入的jar包又在哪里呢?没关系,我们还有另一个插件。如下:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>target/lib</outputDirectory>
<excludeTransitive>false</excludeTransitive>
<stripVersion>false</stripVersion>
<includeScope>runtime</includeScope>
</configuration>
</execution>
</executions>
</plugin>
当你打包的时候自动去生成,如下:
jar包:
这样,就可以把项目中使用到的所有jar包提取出来。
3、配置文件的剔除
项目在大jar包的时候也会把配置文件和页面一起打包,导致每次都要替换或者更改配置文件,导致非常繁琐。
我们可以在打包插件中指定不用打包的内容,如下:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<!--这里是打包的时候排除的文件例如配置文件-->
<excludes>
<exclude>**/*.properties</exclude>
<exclude>**/*.xml</exclude>
<exclude>**/*.yml</exclude>
<exclude>static/**</exclude>
<exclude>templates/**</exclude>
<exclude>**/*.xlsx</exclude>
</excludes>
</configuration>
</plugin>
4、映射配置文件目录
Spring Boot 加载配置文件的方式以及步骤
springboot 默认加载配置文件有三个位置
1、a 加载第二个是 通jar包同级 config目录 下的 一系列配置文件 xxx.yaml
2、b 加载第一个是 同jar包同级的 一系列配置文件xxx.yaml
3、c 加载第三个是 自身jar包的 配置文件。
加载顺序 为: a b c
测试实例 :
a: server.port = 8082
b: server.port = 8081
c: server.port = 8080
结果如下:
5、完整pom
<build>
<finalName>web-discovery-test</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<layout>ZIP</layout>
<includes>
<include>
<groupId>non-exists</groupId>
<artifactId>non-exists</artifactId>
</include>
</includes>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<classifier>classes</classifier>
<attach>false</attach>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>target/lib</outputDirectory>
<excludeTransitive>false</excludeTransitive>
<stripVersion>false</stripVersion>
<includeScope>runtime</includeScope>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<!--这里是打包的时候排除的文件例如配置文件-->
<excludes>
<exclude>**/*.properties</exclude>
<exclude>**/*.xml</exclude>
<exclude>**/*.yml</exclude>
<exclude>static/**</exclude>
<exclude>templates/**</exclude>
<exclude>**/*.xlsx</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
6、启动命令
java -jar -Dloader.path=lib -jar web-discovery-test.jar
java -Dloader.path=lib -jar *.jar
7、制作镜像
制作镜像步骤
1、Dockerfile 文件
## java:8-alpine(145) java8:latest (500m)
FROM java:8-alpine
# 维者信息
MAINTAINER fage
RUN mkdir -p /work /work/config /work/libs /work/logs /work/file
EXPOSE 8080
ADD empty.jar /work/web-discovery-test.jar
WORKDIR /work
CMD ["java","-Dloader.path=/work/libs","-jar","/work/web-discovery-test.jar"]
2、提供相对应的文件
比如:empty.jar
运行命令
docker run -d -p 8080:8080 --name web-discovery-test -v /fage/web-discovery-test/web-discovery-test.jar://work/web-discovery-test.jar -v /fage/web-discovery-test/logs:/work/logs -v /fage/web-discovery-test/libs:/work/libs -v /fage/web-discovery-test/file:/work/file -v /fage/web-discovery-test/config:/work/config web-discovery-test:v2
3、命令构建
docker build -t 镜像名:版本号标签 .
## 实例:
docker build -t web-discovery-test:v1 .
[root@localhost docker]#
[root@localhost docker]# docker build -t web-discovery-test:v2 .
Sending build context to Docker daemon 2.56kB
Step 1/6 : FROM java:8-alpine
8-alpine: Pulling from library/java
709515475419: Pull complete
38a1c0aaa6fd: Pull complete
5b58c996e33e: Pull complete
Digest: sha256:d49bf8c44670834d3dade17f8b84d709e7db47f1887f671a0e098bafa9bae49f
Status: Downloaded newer image for java:8-alpine
---> 3fd9dd82815c
Step 2/6 : RUN mkdir -p /work /work/config /work/libs /work/logs /work/file
---> Running in 4833f98cc891
Removing intermediate container 4833f98cc891
---> 8398b01d5158
Step 3/6 : EXPOSE 8080
---> Running in 6b43e5e32ef7
Removing intermediate container 6b43e5e32ef7
---> 5bde587635f3
Step 4/6 : ADD empty.jar /work/web-discovery-test.jar
---> beed469c2bfe
Step 5/6 : WORKDIR /work
---> Running in d953acaefdc0
Removing intermediate container d953acaefdc0
---> 801c71d84e45
Step 6/6 : CMD ["java","-Dloader.path=/work/libs","-jar","/work/web-discovery-test.jar"]
---> Running in af7a7d89f55b
Removing intermediate container af7a7d89f55b
---> 2f03a2dfcb94
Successfully built 2f03a2dfcb94
Successfully tagged web-discovery-test:v2
[root@localhost docker]#
[root@localhost docker]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
web-discovery-test v2 2f03a2dfcb94 4 seconds ago 145MB
4、其他命令
##进入容器
docker exec -it 容器名 /bin/bash
##查询 xx 相关的镜像
docker search xx
##下载镜像到本地
docker pull 镜像名 (可定义名称 xx:xx)
##查看本地镜像
docker images
##查看正在运行镜像
docker ps (-a 所有启动过的,包括不运行的)
##将容器制作成镜像(内部自定义了一些配置等)
docker commit -m '镜像描述' -a '制作者' 容器名 镜像名
##将制作好的镜像打成 tar 包
docker save -o tar包的名字 镜像名
##怎么使用 tar 包
docker load < tar 包所在路径
5、RUN vs CMD vs ENTRYPOINT区别
-
RUN:执行命令并创建新的镜像层;
-
CMD:设置容器启动后默认执行的命令即参数,但cmd能被docker run后面的命令行参数替换;
-
ENTRYPOINT:配置容器启动时运行的命令。
ENTRYPOINT的Exec格式用于设置要执行的命令及其参数,同时可以通过CMD提供额外的参数。ENTRYPOINT中的参数始终会被用到,而CMD的额外参数可以再容器启动时动态替换。
ENTRYPOINT指令可以让容器以应用程序或者服务的形式运行。和CMD不同的是,ENTRYPOINT不会被忽略,一定会被执行,即使运行docker run时指定了其他命令。
修改镜像名称
[root@localhost ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
pujh/centos tomcat-centos 70ff7873d7cd About an hour ago 612 MB
docker.io/centos latest 9f38484d220f 11 days ago 202 MB
[root@localhost ~]# docker tag 70ff7873d7cd my_centos:tomcat-centos
[root@localhost ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
my_centos tomcat-centos 70ff7873d7cd About an hour ago 612 MB
pujh/centos tomcat-centos 70ff7873d7cd About an hour ago 612 MB
docker.io/centos latest 9f38484d220f 11 days ago 202 MB
[root@localhost ~]# docker rmi 70ff7873d7cd
Error response from daemon: conflict: unable to delete 70ff7873d7cd (cannot be forced) - image is being used by running container 70859e710147
[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
70859e710147 70ff "/bin/sh -c '/root..." About an hour ago Up About an hour 0.0.0.0:8090->8080/tcp dazzling_hopper
[root@localhost ~]# docker stop 70859e710147
[root@localhost ~]# docker rm 70859e710147
[root@localhost ~]# docker rmi 70ff7873d7cd
[root@localhost ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
my_centos tomcat-centos 70ff7873d7cd About an hour ago 612 MB
docker.io/centos latest 9f38484d220f 11 days ago 202 MB
### IMAGE ID 一样,无法删除
[root@localhost /]# docker rmi 00bc163fa009
Error response from daemon: conflict: unable to delete 00bc163fa009 (must be forced) - image is referenced in multiple repositories
[root@localhost /]# docker rmi williamyeh/java8:latest
Untagged: williamyeh/java8:latest
Untagged: williamyeh/java8@sha256:174d528516a0eae5c4df69966eeb5e51d7c0dc1a532249af61013953eab1d9f3
8、Spring Boot日志
Spring Boot 默认使用logback日志。
1、使用动态配置
开发与生产配置隔离,分开配置
application.properties
## 开发环境 dev /生产环境 product
spring.profiles.active=dev
application-dev.yaml
## 日志配置 配置绝对路径,不要使用相对路径
logging:
file:
path: D:\logs\dev
## 其他配置
server:
port: 8084
application-product.yaml
## 日志配置 配置绝对路径,不要使用相对路径
logging:
file:
path: D:\logs\product
## 其他配置
server:
port: 80
2、logback配置
logback-spring.xml配置
一定要加 -spring ,表示在spring配置被加载之后才执行,当前的logback配置,
<!-- spring 配置 -->
<springProperty scope="context" name="logPath" source="logging.file.path"/>
<springProperty scope="context" name="logname" source="spring.application.name"/>
动态传入配置信息
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="10 seconds">
<contextName>logback</contextName>
<!-- spring 配置 -->
<springProperty scope="context" name="logPath" source="logging.file.path"/>
<springProperty scope="context" name="logname" source="spring.application.name"/>
<!-- 设置 颜色,从 org.springframework.boot.logging.logback 下 的 xml 获取 -->
<conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter"/>
<conversionRule conversionWord="wex"
converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter"/>
<conversionRule conversionWord="wEx"
converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter"/>
<property name="CONSOLE_LOG_PATTERN"
value="${CONSOLE_LOG_PATTERN:-%clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<property name="FILE_LOG_PATTERN"
value="${FILE_LOG_PATTERN:-%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}} ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- [%t] %-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<logger name="org.apache.catalina.startup.DigesterFactory" level="ERROR"/>
<logger name="org.apache.catalina.util.LifecycleBase" level="ERROR"/>
<logger name="org.apache.coyote.http11.Http11NioProtocol" level="WARN"/>
<logger name="org.apache.sshd.common.util.SecurityUtils" level="WARN"/>
<logger name="org.apache.tomcat.util.net.NioSelectorPool" level="WARN"/>
<logger name="org.eclipse.jetty.util.component.AbstractLifeCycle" level="ERROR"/>
<logger name="org.hibernate.validator.internal.util.Version" level="WARN"/>
<logger name="org.springframework.boot.actuate.endpoint.jmx" level="WARN"/>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<target>System.out</target>
<!--此日志appender是为开发使用,只配置最底级别,控制台输出的日志级别是大于或等于此级别的日志信息-->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>debug</level>
</filter>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<!-- 设置字符集 FATAL_FILE-->
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- 时间滚动输出 level为 DEBUG 日志 -->
<appender name="DEBUG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<!--<file>${logPath}/log_debug.log</file>-->
<!--日志文件输出格式-->
<encoder>
<pattern>${FILE_LOG_PATTERN}</pattern>
<charset>UTF-8</charset> <!-- 设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志归档 -->
<fileNamePattern>${logPath}/debug/log-debug-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录debug级别的 -->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>debug</level>
</filter>
</appender>
<!-- 时间滚动输出 level为 INFO 日志 -->
<appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<!--<file>${logPath}/log_info.log</file>-->
<!--日志文件输出格式-->
<encoder>
<pattern>${FILE_LOG_PATTERN}</pattern>
<charset>UTF-8</charset>
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 每天日志归档路径以及格式 -->
<fileNamePattern>${logPath}/info/log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录info级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>info</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 ERROR 日志 -->
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<!--<file>${logPath}/log_error.log</file>-->
<!--日志文件输出格式-->
<encoder>
<pattern>${FILE_LOG_PATTERN}</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${logPath}/error/log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录ERROR级别的 -->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
</appender>
<!--开发环境:打印控制台;自定义设置包下面的日志打印级别-->
<!-- <springProfile name="dev">-->
<!-- <logger name="com.spring.boot.springbootdemo.mapper" level="debug"/>-->
<!-- </springProfile>-->
<root level="info">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="DEBUG_FILE"/>
<appender-ref ref="INFO_FILE"/>
<appender-ref ref="ERROR_FILE"/>
</root>
</configuration>
9、Linux 删除目录的命令
-r 就是向下递归,不管有多少级目录,一并删除 -f 就是直接强行删除,不作任何提示的意思
删除文件夹实例:
rm -rf /var/log/httpd/access
将会删除/var/log/httpd/access目录以及其下所有文件、文件夹
删除文件使用实例:
rm -f /var/log/httpd/access.log
将会强制删除/var/log/httpd/access.log这个文件
10、实战测试
1、项目结构
2、服务器结构
3、镜像
docker build -t web-discovery-test:v1 .
可以发现,这个jar是非常的小
4、执行结果
运行命令
docker run -d -p 8080:8080 --name web-discovery-test -v /fage/web-discovery-test/web-discovery-test.jar://work/web-discovery-test.jar -v /fage/web-discovery-test/logs:/work/logs -v /fage/web-discovery-test/libs:/work/libs -v /fage/web-discovery-test/file:/work/file -v /fage/web-discovery-test/config:/work/config web-discovery-test:v2
运行结果查看
日志打印
[root@localhost docker]# docker logs -f b2b3eaee4b81
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.2.RELEASE)
2020-08-06 14:14:17.080 INFO 1 --- [ main] com.fage.demo.DemoApplication : Starting DemoApplication v0.0.1-SNAPSHOT on b2b3eaee4b81 with PID 1 (/work/web-discovery-test.jar started by root in /work)
2020-08-06 14:14:17.084 INFO 1 --- [ main] com.fage.demo.DemoApplication : The following profiles are active: product
2020-08-06 14:14:18.863 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-08-06 14:14:18.880 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-08-06 14:14:18.892 INFO 1 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-08-06 14:14:19.026 INFO 1 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-08-06 14:14:19.026 INFO 1 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1835 ms
2020-08-06 14:14:19.892 INFO 1 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-08-06 14:14:20.374 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-08-06 14:14:20.403 INFO 1 --- [ main] com.fage.demo.DemoApplication : Started DemoApplication in 4.073 seconds (JVM running for 4.615)
2020-08-06 14:15:04.855 INFO 1 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-08-06 14:15:04.855 INFO 1 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-08-06 14:15:04.871 INFO 1 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 16 ms
2020-08-06 14:15:04.928 INFO 1 --- [nio-8080-exec-1] com.fage.demo.DemoApplication : file.isDirectory() = true
2020-08-06 14:15:35.456 INFO 1 --- [nio-8080-exec-4] com.fage.demo.DemoApplication : hello world
2020-08-06 14:15:35.457 ERROR 1 --- [nio-8080-exec-4] com.fage.demo.DemoApplication : error
2020-08-06 14:16:12.006 INFO 1 --- [nio-8080-exec-6] com.fage.demo.DemoApplication : hello world
2020-08-06 14:16:12.012 ERROR 1 --- [nio-8080-exec-6] com.fage.demo.DemoApplication : error
2020-08-06 14:16:15.305 INFO 1 --- [nio-8080-exec-7] com.fage.demo.DemoApplication : file.isDirectory() = true
2020-08-06 14:16:15.306 INFO 1 --- [nio-8080-exec-7] com.fage.demo.DemoApplication : 文件夹: /work/file/mk
2020-08-06 14:16:15.306 INFO 1 --- [nio-8080-exec-7] com.fage.demo.DemoApplication : 文件: /work/file/aaa
验证 是否映射成功?调用接口:http://192.168.71.134:8080/files和http://192.168.71.134:8080/hello
日志打印:
2020-08-06 14:16:15.305 INFO 1 --- [nio-8080-exec-7] com.fage.demo.DemoApplication : file.isDirectory() = true
2020-08-06 14:16:15.306 INFO 1 --- [nio-8080-exec-7] com.fage.demo.DemoApplication : 文件夹: /work/file/mk
2020-08-06 14:16:15.306 INFO 1 --- [nio-8080-exec-7] com.fage.demo.DemoApplication : 文件: /work/file/aaa
微信公众号 点击关于我,加入QQ群,即可获取到代码
这是一个稍偏基础和偏技术的公众号,甚至其中包括一些可能阅读量很低的包含代码的技术文,不知道你是不是喜欢,期待你的关注。
如果你觉得文章还不错,就请点击右上角选择发送给朋友或者转发到朋友圈~
据说看到好文章不推荐的人,服务器容易宕机!