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群,即可獲取到代碼
這是一個稍偏基礎和偏技術的公眾號,甚至其中包括一些可能閱讀量很低的包含代碼的技術文,不知道你是不是喜歡,期待你的關注。
如果你覺得文章還不錯,就請點擊右上角選擇發送給朋友或者轉發到朋友圈~
據說看到好文章不推薦的人,服務器容易宕機!
本文版權歸 發哥講 和 博客園 共有,原創文章,未經允許不得轉載,否則保留追究法律責任的權利。