Spring Boot deployment
1. Spring Boot deploymentoverview
Spring Boot application可以through many 种方式deployment, including传统 WAR packagedeployment, 可执行 JAR packagedeployment, containerizationdeployment以及云平台deployment.
1.1 deploymentclass型
- 可执行 JAR package - Spring Boot 推荐 deployment方式, package含嵌入式server
- WAR package - 传统 Java Web applicationdeployment方式, 需要 out 部 Servlet containers
- containerizationdeployment - using Docker containersdeployment
- 云平台deployment - deployment to AWS, Azure, GCP etc.云平台
- Kubernetes deployment - containersorchestration and management
2. 打package可执行 JAR package
Spring Boot application默认using可执行 JAR packagefordeployment, in 置了 Tomcat, Jetty or Undertow server.
2.1 Maven configuration
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
2.2 打packagecommands
# using Maven 打package
mvn clean package
# using Gradle 打package
gradle clean build
2.3 run JAR package
# basicrun方式
java -jar target/myapp-0.0.1-SNAPSHOT.jar
# 指定configurationfilerun
java -jar -Dspring.profiles.active=prod target/myapp-0.0.1-SNAPSHOT.jar
# 指定端口run
java -jar -Dserver.port=8081 target/myapp-0.0.1-SNAPSHOT.jar
# after 台run
nohup java -jar target/myapp-0.0.1-SNAPSHOT.jar > myapp.log 2>&1 &
# 查看 after 台runprocess
ps aux | grep myapp
# 停止 after 台process
kill
3. 打package WAR package
such as果需要将 Spring Boot applicationdeployment to out 部 Servlet containers, 可以打package for WAR package.
3.1 modify打package方式
<packaging>war</packaging>
3.2 modify主class
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationbuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationbuilder configure(SpringApplicationbuilder application) {
return application.sources(DemoApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
3.3 排除 in 置server
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<scope>provided</scope>
</dependency>
3.4 deployment to out 部containers
- Tomcat - 将 WAR packagecopy to
webappsTable of Contents - Jetty - 将 WAR packagecopy to
webappsTable of Contents - WildFly - usingmanagement控制台 or copy to
standalone/deploymentsTable of Contents
4. Docker containerizationdeployment
using Docker containerization Spring Boot application可以简化deployment and management.
4.1 creation Dockerfile
# using官方 OpenJDK 镜像serving asBasics镜像
FROM openjdk:17-jdk-slim
# 设置工作Table of Contents
WORKDIR /app
# copy Maven 构建 JAR file to containersin
COPY target/myapp-0.0.1-SNAPSHOT.jar app.jar
# 暴露application端口
EXPOSE 8080
# 设置environmentvariable
ENV SPRING_PROFILES_ACTIVE=prod
# runapplication
ENTRYPOINT ["java", "-jar", "app.jar"]
4.2 构建 Docker 镜像
# 构建镜像
docker build -t myapp:1.0 .
# 查看镜像
docker images
4.3 run Docker containers
# basicrun
docker run -d -p 8080:8080 --name myapp myapp:1.0
# run并挂载configurationfile
docker run -d -p 8080:8080 \
-v /host/path/application.properties:/app/application.properties \
--name myapp myapp:1.0
# run并设置environmentvariable
docker run -d -p 8080:8080 \
-e SPRING_PROFILES_ACTIVE=prod \
-e DATABASE_URL=jdbc:mysql://db:3306/mydb \
--name myapp myapp:1.0
# 查看runin containers
docker ps
# 查看containerslog
docker logs -f myapp
# 停止containers
docker stop myapp
# deletecontainers
docker rm myapp
4.4 using Docker Compose
# docker-compose.yml
version: '3.8'
services:
app:
build: .
ports:
- "8080:8080"
environment:
- SPRING_PROFILES_ACTIVE=prod
- DATABASE_URL=jdbc:mysql://db:3306/mydb
depends_on:
- db
restart: unless-stopped
db:
image: mysql:8.0
environment:
- MYSQL_DATABASE=mydb
- MYSQL_USER=myuser
- MYSQL_PASSWORD=mypassword
- MYSQL_ROOT_PASSWORD=rootpassword
volumes:
- mysql_data:/var/lib/mysql
restart: unless-stopped
volumes:
mysql_data:
# 启动service
docker-compose up -d
# 查看servicestatus
docker-compose ps
# 查看servicelog
docker-compose logs -f
# 停止service
docker-compose down
# 停止service并delete卷
docker-compose down -v
5. Kubernetes deployment
Kubernetes is a open-source containersorchestration平台, 用于automationcontainers deployment, scale and management.
5.1 deployment YAML file
# deployment.yml
apiVersion: apps/v1
kind: deploymentment
metadata:
name: myapp-deployment
labels:
app: myapp
spec:
replicas: 3
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
containers:
- name: myapp
image: myapp:1.0
ports:
- containerPort: 8080
env:
- name: SPRING_PROFILES_ACTIVE
value: "prod"
- name: DATABASE_URL
value: "jdbc:mysql://mysql-service:3306/mydb"
resources:
limits:
cpu: "500m"
memory: "512Mi"
requests:
cpu: "200m"
memory: "256Mi"
livenessProbe:
httpGet:
path: /actuator/health/liveness
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
initialDelaySeconds: 10
periodSeconds: 5
# service.yml
apiVersion: v1
kind: Service
metadata:
name: myapp-service
spec:
selector:
app: myapp
ports:
- port: 80
targetPort: 8080
protocol: TCP
type: LoadBalancer
5.2 applicationdeployment
# applicationdeploymentfile
kubectl apply -f deployment.yml -f service.yml
# 查看deploymentstatus
kubectl get deployments
# 查看 Pod status
kubectl get pods
# 查看servicestatus
kubectl get services
# 查看 Pod log
kubectl logs myapp-deployment-xxxxxxxxxx-xxxxx
# scalereplica数量
kubectl scale deployment myapp-deployment --replicas=5
# updatedeployment
kubectl set image deployment/myapp-deployment myapp=myapp:2.0
# rollbackdeployment
kubectl rollout undo deployment/myapp-deployment
6. 云平台deployment
Spring Boot application可以deployment to 各 big 云平台, such as AWS, Azure, GCP etc..
6.1 AWS deployment选项
- Elastic Beanstalk - 全托管 applicationdeploymentservice
- ECS - containersservice, support Docker containers
- EKS - Kubernetes service
- EC2 - 虚拟机直接deployment
- Lambda - 无serverfunction计算
6.2 Azure deployment选项
- Azure App Service - 全托管 Web applicationservice
- Azure Kubernetes Service (AKS) - Kubernetes service
- Azure Container Instances - containersinstance
- Azure Functions - 无serverfunction
6.3 Google Cloud deployment选项
- App Engine - 全托管 application平台
- Google Kubernetes Engine (GKE) - Kubernetes service
- Cloud Run - 无servercontainers平台
- Compute Engine - 虚拟机
7. configurationmanagement
in 不同environmentindeployment Spring Boot application时, 需要 has 效 configurationmanagement策略.
7.1 environmentvariableconfiguration
# operationsystemenvironmentvariable
export SPRING_PROFILES_ACTIVE=prod
export DATABASE_URL=jdbc:mysql://localhost:3306/mydb
export SPRING_DATASOURCE_URL=jdbc:mysql://localhost:3306/mydb
export SPRING_DATASOURCE_USERNAME=root
export SPRING_DATASOURCE_PASSWORD=password
7.2 configurationfilepriority
Spring Boot configurationfile加载priority ( from high to low ) :
- commands行parameter
- Java systemproperty (System.getProperties())
- operationsystemenvironmentvariable
- application-{profile}.properties or application-{profile}.yml ( out 部)
- application-{profile}.properties or application-{profile}.yml ( in 部)
- application.properties or application.yml ( out 部)
- application.properties or application.yml ( in 部)
7.3 out 部configurationsources
- Spring Cloud Config - 集in式configurationmanagement
- HashiCorp Vault - security key and configurationmanagement
- Consul - service发现 and configurationmanagement
- AWS Parameter Store - AWS configurationstore
- Azure Key Vault - Azure keymanagement
8. monitor and management
deployment after 需要monitorapplication runstatus and performance.
8.1 Spring Boot Actuator
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
# configuration Actuator
management.endpoints.web.exposure.include=*management.endpoint.health.show-details=always
management.endpoint.metrics.enabled=true
management.endpoint.prometheus.enabled=true
# Prometheus 集成
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
8.2 monitortool
- Prometheus - monitor and 告警
- Grafana - datavisualization
- ELK Stack - log收集 and analysis
- Zipkin - distributed追踪
- New Relic - applicationperformancemonitor
- Dynatrace - 全栈monitor
8.3 healthycheck端点
/actuator/health- applicationhealthystatus/actuator/info- applicationinformation/actuator/metrics- application指标/actuator/prometheus- Prometheus 指标/actuator/env- environmentvariable/actuator/loggers- logconfiguration
9. deploymentbest practices
9.1 构建 and deployment
- using CI/CD pipelineautomation构建 and deployment
- using语义化version控制
- implementation蓝绿deployment or 金丝雀release
- 保持构建 可重复性
- using Docker 镜像serving asdeployment单元
9.2 configurationmanagement
- 分离configuration and code
- usingenvironmentvariable or configurationin心
- encryption敏感configuration
- implementationconfiguration热update
- using不同 configurationfile or configurationfile
9.3 monitor and log
- implementation全面 healthycheck
- 收集关键指标
- implementationdistributed追踪
- 集inmanagementlog
- 设置合理 告警规则
9.4 security性
- using HTTPS
- configuration适当 CORS 策略
- 定期update依赖
- 实施最 small permissionprinciples
- usingsecurity containers镜像
- implementation适当 访问控制
10. commondeploymentissues及solution
10.1 端口conflict
- using不同 端口号run many 个instance
- in Docker inmap不同 主机端口
- in Kubernetes inusing Service forload balancing
10.2 memory不足
- 调整 JVM 堆 big small :
-Xms512m -Xmx1024m - optimizationapplicationcode, reducingmemoryusing
- 增加containers or 虚拟机 memoryresource
10.3 datalibrary连接issues
- checkdatalibrary连接string
- verificationdatalibrary凭据
- checkdatalibraryserverstatus
- configuration适当 连接池parameter
10.4 configurationerror
- checkconfigurationfile语法
- verificationenvironmentvariable设置
- 查看applicationlogin errorinformation
- using Actuator /env 端点checkconfiguration