Preface
With the popularity of microservice architecture, how to efficiently deploy and manage these distributed services has become an important challenge for developers. Spring Boot has become an ideal framework for building microservices with its simplified configuration and rapid development features; while Docker and Kubernetes solve the containerization and orchestration of services respectively. This article will introduce in detail how to containerize the microservices developed by Spring Boot through Docker and deploy and manage them using Kubernetes, helping readers master the complete development and deployment process of modern cloud-native applications.
Part 1: Introduction to the microservice architecture
What is a microservice
Microservices are an architectural style that builds applications into a series of small, autonomous services, each running in its own process and communicating through a lightweight mechanism (usually an HTTP API). These services are built around business capabilities and can be deployed independently through a fully automatic deployment mechanism.
Advantages of microservices
Technical heterogeneity: Different services can use different technology stacks
Elasticity: The failure of a single component does not cause the entire application to crash
Scalability: You can only scale the services that need to be expanded, not the entire application
Easy to deploy: Services can be deployed independently without affecting other services
Organizational alignment: Small teams can focus on specific services
The challenge of microservices
The complexity of distributed systems
Reliability of communication between services
Data consistency
Increased operation and maintenance complexity
Part 2: Spring Boot Microservice Development
Introduction to Spring Boot
Spring Boot is a framework that simplifies Spring application development. It eliminates the tedious configuration process in traditional Spring applications and provides many "out-of-the-box" functions.
Create a simple Spring Boot microservice
1. Project structure
demo-service/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── example/
│ │ │ └── demo/
│ │ │ ├──
│ │ │ ├── controller/
│ │ │ │ └──
│ │ │ ├── service/
│ │ │ │ └──
│ │ │ └── model/
│ │ │ └──
│ │ └── resources/
│ │ └──
├──
└── Dockerfile
2. Configuration
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="/POM/4.0.0" xmlns:xsi="http:///2001/XMLSchema-instance" xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0."> <modelVersion>4.0.0</modelVersion> <parent> <groupId></groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.0</version> </parent> <groupId></groupId> <artifactId>demo-service</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <>11</> </properties> <dependencies> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId></groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
3. Apply the main class
package ; import ; import ;@SpringBootApplication public class DemoApplication { public static void main(String[] args) { (, args); } }
4. Controller
package ; import ; import ; @RestController public class DemoController { @GetMapping("/hello") public String hello() { return "Hello from Spring Boot Microservice!"; } }
5. Configuration file
server: port: 8080 spring: application: name: demo-service management: endpoints: web: exposure: include: health,info,metrics
Microservice communication
In microservice architecture, inter-service communication is usually implemented in the following ways:
- REST API: The most common way of communication, based on HTTP protocol
- Message queue: such as RabbitMQ, Kafka, etc., suitable for asynchronous communication
- Service Discovery: For example, Eureka, Consul, help services find each other
- API gateway: such as Spring Cloud Gateway, provides a unified API portal
Part 3: Docker containerization
Introduction to Docker
Docker is an open source application container engine that allows developers to package applications and their dependencies into a portable container and publish them to any popular Linux or Windows machine.
The core concept of Docker
Image: The template of the Docker container, containing all the files and configurations required to run the application
Container: A mirror running instance
Dockerfile: script file used to build Docker images
Docker Hub: Public Docker Image Repository
Create a Dockerfile for Spring Boot app
FROM openjdk:11-jre-slim WORKDIR /app COPY target/demo-service-0.0. EXPOSE 8080 ENTRYPOINT ["java", "-jar", ""]
Build and run Docker images
# Build Spring Boot Applicationmvn clean package # Build Docker Imagedocker build -t demo-service:latest . # Run Docker containerdocker run -p 8080:8080 demo-service:latest
Multi-stage construction optimization
To reduce the size of the final image, a multi-stage build can be used:
# Build phaseFROM maven:3.8.5-openjdk-11-slim AS build WORKDIR /app COPY . COPY src ./src RUN mvn clean package -DskipTests # Running phaseFROM openjdk:11-jre-slim WORKDIR /app COPY --from=build /app/target/demo-service-0.0. EXPOSE 8080 ENTRYPOINT ["java", "-jar", ""]
Docker Compose manages multi-services
For applications containing multiple microservices, you can use Docker Compose to manage:
# version: '3' services: demo-service: build: ./demo-service ports: - "8080:8080" environment: - SPRING_PROFILES_ACTIVE=docker depends_on: - db user-service: build: ./user-service ports: - "8081:8081" environment: - SPRING_PROFILES_ACTIVE=docker depends_on: - db db: image: mysql:8.0 environment: - MYSQL_ROOT_PASSWORD=password - MYSQL_DATABASE=microservices volumes: - db-data:/var/lib/mysql ports: - "3306:3306" volumes: db-data:
Part 4: Kubernetes Orchestration and Deployment
Introduction to Kubernetes
Kubernetes (K8s) is an open source container orchestration platform for automating the deployment, scaling and management of containerized applications.
The core concept of Kubernetes
Pod: The smallest deployment unit in K8s that can contain one or more containers
Service: Provide a unified network access policy for a group of pods
Deployment: Manage Pod creation and update
ConfigMap/Secret: Manage configuration and sensitive information
Namespace: Provide resource isolation
Ingress: Manage HTTP routing for external access to services within the cluster
Deploy Spring Boot Microservices to Kubernetes
1. Create a Deployment configuration
# apiVersion: apps/v1 kind: Deployment metadata: name: demo-service labels: app: demo-service spec: replicas: 3 selector: matchLabels: app: demo-service template: metadata: labels: app: demo-service spec: containers: - name: demo-service image: demo-service:latest imagePullPolicy: IfNotPresent ports: - containerPort: 8080 resources: limits: cpu: "0.5" memory: "512Mi" requests: cpu: "0.2" memory: "256Mi" livenessProbe: httpGet: path: /actuator/health port: 8080 initialDelaySeconds: 30 periodSeconds: 10 readinessProbe: httpGet: path: /actuator/health port: 8080 initialDelaySeconds: 5 periodSeconds: 5
2. Create Service Configuration
# apiVersion: v1 kind: Service metadata: name: demo-service spec: selector: app: demo-service ports: - port: 80 targetPort: 8080 type: ClusterIP
3. Create Ingress Configuration
# apiVersion: networking./v1 kind: Ingress metadata: name: demo-ingress annotations: /rewrite-target: / spec: rules: - host: http: paths: - path: / pathType: Prefix backend: service: name: demo-service port: number: 80
4. Application configuration to Kubernetes cluster
# Deploy the applicationkubectl apply -f kubectl apply -f kubectl apply -f # Check deployment statuskubectl get deployments kubectl get pods kubectl get services kubectl get ingress
Configuration Management
Use ConfigMap to manage application configuration:
# apiVersion: v1 kind: ConfigMap metadata: name: demo-config data: : | server: port: 8080 spring: application: name: demo-service
Then quote in Deployment:
volumes: - name: config-volume configMap: name: demo-config containers: - name: demo-service volumeMounts: - name: config-volume mountPath: /app/config env: - name: SPRING_CONFIG_LOCATION value: file:/app/config/
Automatic expansion
Configure Horizontal Pod Autoscaler (HPA):
# apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler metadata: name: demo-service-hpa spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: demo-service minReplicas: 2 maxReplicas: 10 metrics: - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 70
Part 5: Monitoring and Maintenance
Application monitoring
1. Spring Boot Actuator
Spring Boot Actuator provides functions to monitor and manage Spring Boot applications in production environments, such as health checks, metric collection, etc.
Actuator configuration in #management: endpoints: web: exposure: include: health,info,metrics,prometheus endpoint: health: show-details: always
2. Prometheus and Grafana
Prometheus: Used to collect and store metric data
Grafana: used to visualize monitoring data
Deploy Prometheus:
# apiVersion: v1 kind: ConfigMap metadata: name: prometheus-config data: : | global: scrape_interval: 15s scrape_configs: - job_name: 'spring-boot-app' metrics_path: '/actuator/prometheus' kubernetes_sd_configs: - role: pod relabel_configs: - source_labels: [__meta_kubernetes_pod_label_app] action: keep regex: demo-service
Log Management
Logs were collected and analyzed using ELK (Elasticsearch, Logstash, Kibana) or EFK (Elasticsearch, Fluentd, Kibana) stack.
Fluentd configuration example:
# apiVersion: v1 kind: ConfigMap metadata: name: fluentd-config data: : | <source> @type tail path /var/log/containers/*.log pos_file /var/log/ tag kubernetes.* read_from_head true <parse> @type json time_format %Y-%m-%dT%H:%M:%S.%NZ </parse> </source> <match .**> @type elasticsearch host elasticsearch-logging port 9200 logstash_format true logstash_prefix k8s <buffer> @type file path /var/log/fluentd-buffers/ flush_mode interval retry_type exponential_backoff flush_thread_count 2 flush_interval 5s </buffer> </match>
CI/CD pipeline
Build CI/CD pipelines with Jenkins, GitLab CI, or GitHub Actions for automated build, testing, and deployment.
GitHub Actions workflow example:
# .github/workflows/ name: CI/CD Pipeline on: push: branches: [ main ] pull_request: branches: [ main ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up JDK 11 uses: actions/setup-java@v2 with: java-version: '11' distribution: 'adopt' - name: Build with Maven run: mvn clean package -DskipTests - name: Build and push Docker image uses: docker/build-push-action@v2 with: context: . push: true tags: user/demo-service:latest deploy: needs: build runs-on: ubuntu-latest steps: - name: Deploy to Kubernetes uses: steebchen/kubectl@master with: config: ${{ secrets.KUBE_CONFIG_DATA }} command: apply -f k8s/
Summarize
This article details how to use Spring Boot to develop microservices, containerize them through Docker, and deploy and manage them using Kubernetes. This combination has become the standard technology stack for modern cloud-native applications, and mastering these technologies is crucial for development and operation and maintenance personnel.
By following this article’s practical guide, you can:
- Rapidly develop microservices with Spring Boot
- Contains microservices to achieve environmental consistency
- Use Kubernetes for service orchestration to achieve high availability deployment
- Establish a complete monitoring and logging system
- Implementing automated CI/CD pipelines
With the continuous development of cloud-native technology, these technologies and practices are also evolving. It is recommended that readers continue to pay attention to the updates of relevant technologies and continuously optimize their microservice architecture and deployment strategies.
The above is the detailed content of Springboot development using Docker and Kubernetes to deploy microservices. For more information about Docker Kubernetes to deploy microservices, please follow my other related articles!