在Kubernetes上部署Spring Boot应用程序

一、前言

本指南将引导你完成在Kubernetes上部署Spring Boot应用程序。你可以有许多方法使用Spring Boot和Kubernetes。本指南的目的是让你尽快开展工作,而不是讨论所有的可能替代方案,也不是深入探讨如何进入生产的所有细节。本指南使用 Docker Desktop 运行单节点 Kubernetes,以快速实现在 Kubernetes 上开展工作。使用Spring Boot提供的探针进行有效性探测。

二、环境准备

  • Docker Desktop;

  • 并且“Enable Kubernetes”,Start a Kubernetes single-node cluster when starting Docker Desktop;

  • 启动 Docker,并且执行一下命令,以修复 macOS 上执行 spring-boot:build-image 时找不到 docker.sock;

    sudo ln -sf "$HOME/.docker/run/docker.sock" /var/run/docker.sock
    

    如果不执行上面的命令,会出现以下错误,这是由于在docker的某个版本把docker.sock的文件位置作了修改,但是其他配套厂商还没有进行修改。

    [INFO]  > Pulling builder image 'docker.io/paketobuildpacks/builder:base' 100%
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD FAILURE
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time:  5.888 s
    [INFO] Finished at: 2023-04-18T15:20:06+08:00
    [INFO] ------------------------------------------------------------------------
    [ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:3.0.5:build-image (default-cli) on project demo: Execution default-cli of goal org.springframework.boot:spring-boot-maven-plugin:3.0.5:build-image failed: Connection to the Docker daemon at 'localhost' failed with error "[2] No such file or directory"; ensure the Docker daemon is running and accessible: com.sun.jna.LastErrorException: [2] No such file or directory -> [Help 1]
    [ERROR] 
    [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
    [ERROR] Re-run Maven using the -X switch to enable full debug logging.
    [ERROR] 
    [ERROR] For more information about the errors and possible solutions, please read the following articles:
    [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException
    mark-vivv@MBP demo %
    
  • spring initializr 下载一个实例程序。点击前方链接,获得一个 Spring Boot 3.0.5 并配置了 Spring Reactive Web、Spring Boot Actuator 的示例程序;

  • 使用 IDEA 打开解压缩之后的 demo 文件。

三、执行编译

mark-vivv@MBP demo % ./mvnw spring-boot:build-image

输出的日志内容如下,最后可以看到输出Successfully built image 'docker.io/library/demo:0.0.1-SNAPSHOT',此时镜像文件已经写入 docker images。

[INFO] Scanning for projects...
[INFO] 
[INFO] --------------------------< com.example:demo >--------------------------
[INFO] Building demo 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] >>> spring-boot-maven-plugin:3.0.5:build-image (default-cli) > package @ demo >>>
[INFO] 
[INFO] --- maven-resources-plugin:3.3.0:resources (default-resources) @ demo ---
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.10.1:compile (default-compile) @ demo ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-resources-plugin:3.3.0:testResources (default-testResources) @ demo ---
[INFO] skip non existing resourceDirectory /Users/mark-vivv/dev/IdeaProjects/demo/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.10.1:testCompile (default-testCompile) @ demo ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) @ demo ---
[INFO] 
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.example.demo.DemoApplicationTests

......

[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.568 s - in com.example.demo.DemoApplicationTests
[INFO] 
[INFO] Results:
[INFO] 
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] 
[INFO] 
[INFO] --- maven-jar-plugin:3.3.0:jar (default-jar) @ demo ---
[INFO] 
[INFO] --- spring-boot-maven-plugin:3.0.5:repackage (repackage) @ demo ---
[INFO] Replacing main artifact with repackaged archive
[INFO] 
[INFO] <<< spring-boot-maven-plugin:3.0.5:build-image (default-cli) < package @ demo <<<
[INFO] 
[INFO] 
[INFO] --- spring-boot-maven-plugin:3.0.5:build-image (default-cli) @ demo ---
[INFO] Building image 'docker.io/library/demo:0.0.1-SNAPSHOT'
[INFO] 
[INFO]  > Pulling builder image 'docker.io/paketobuildpacks/builder:base' 100%
[INFO]  > Pulled builder image 'paketobuildpacks/builder@sha256:dd98964477407e67eb6620450c4f4a5d2236f8fdc8e6569ce3778318aa4b7e64'
[INFO]  > Pulling run image 'docker.io/paketobuildpacks/run:base-cnb' 100%
[INFO]  > Pulled run image 'paketobuildpacks/run@sha256:41443690a2dc36118112db2c4790dc2bc8189926dae9ff91992b78675d0cac39'
[INFO]  > Executing lifecycle version v0.16.1
[INFO]  > Using build cache volume 'pack-cache-5cbe5692dbc4.build'
[INFO] 
[INFO]  > Running creator
[INFO]     [creator]     ===> ANALYZING
[INFO]     [creator]     Restoring data for SBOM from previous image
[INFO]     [creator]     ===> DETECTING
[INFO]     [creator]     6 of 26 buildpacks participating
[INFO]     [creator]     paketo-buildpacks/ca-certificates   3.6.1
[INFO]     [creator]     paketo-buildpacks/bellsoft-liberica 10.1.0
[INFO]     [creator]     paketo-buildpacks/syft              1.28.0
[INFO]     [creator]     paketo-buildpacks/executable-jar    6.6.3
[INFO]     [creator]     paketo-buildpacks/dist-zip          5.5.2
[INFO]     [creator]     paketo-buildpacks/spring-boot       5.23.0
[INFO]     [creator]     ===> RESTORING
[INFO]     [creator]     Restoring metadata for "paketo-buildpacks/ca-certificates:helper" from app image
[INFO]     [creator]     Restoring metadata for "paketo-buildpacks/bellsoft-liberica:helper" from app image
[INFO]     [creator]     Restoring metadata for "paketo-buildpacks/bellsoft-liberica:java-security-properties" from app image
[INFO]     [creator]     Restoring metadata for "paketo-buildpacks/bellsoft-liberica:jre" from app image
[INFO]     [creator]     Restoring metadata for "paketo-buildpacks/syft:syft" from cache
[INFO]     [creator]     Restoring metadata for "paketo-buildpacks/spring-boot:helper" from app image
[INFO]     [creator]     Restoring metadata for "paketo-buildpacks/spring-boot:spring-cloud-bindings" from app image
[INFO]     [creator]     Restoring metadata for "paketo-buildpacks/spring-boot:web-application-type" from app image
[INFO]     [creator]     Restoring data for "paketo-buildpacks/syft:syft" from cache
[INFO]     [creator]     Restoring data for SBOM from cache
[INFO]     [creator]     ===> BUILDING
[INFO]     [creator]     
[INFO]     [creator]     Paketo Buildpack for CA Certificates 3.6.1
[INFO]     [creator]       https://github.com/paketo-buildpacks/ca-certificates
[INFO]     [creator]       Launch Helper: Reusing cached layer
[INFO]     [creator]     
[INFO]     [creator]     Paketo Buildpack for BellSoft Liberica 10.1.0
[INFO]     [creator]       https://github.com/paketo-buildpacks/bellsoft-liberica
[INFO]     [creator]       Build Configuration:
[INFO]     [creator]         $BP_JVM_JLINK_ARGS           --no-man-pages --no-header-files --strip-debug --compress=1  configure custom link arguments (--output must be omitted)
[INFO]     [creator]         $BP_JVM_JLINK_ENABLED        false                                                        enables running jlink tool to generate custom JRE
[INFO]     [creator]         $BP_JVM_TYPE                 JRE                                                          the JVM type - JDK or JRE
[INFO]     [creator]         $BP_JVM_VERSION              17                                                           the Java version
[INFO]     [creator]       Launch Configuration:
[INFO]     [creator]         $BPL_DEBUG_ENABLED           false                                                        enables Java remote debugging support
[INFO]     [creator]         $BPL_DEBUG_PORT              8000                                                         configure the remote debugging port
[INFO]     [creator]         $BPL_DEBUG_SUSPEND           false                                                        configure whether to suspend execution until a debugger has attached
[INFO]     [creator]         $BPL_HEAP_DUMP_PATH                                                                       write heap dumps on error to this path
[INFO]     [creator]         $BPL_JAVA_NMT_ENABLED        true                                                         enables Java Native Memory Tracking (NMT)
[INFO]     [creator]         $BPL_JAVA_NMT_LEVEL          summary                                                      configure level of NMT, summary or detail
[INFO]     [creator]         $BPL_JFR_ARGS                                                                             configure custom Java Flight Recording (JFR) arguments
[INFO]     [creator]         $BPL_JFR_ENABLED             false                                                        enables Java Flight Recording (JFR)
[INFO]     [creator]         $BPL_JMX_ENABLED             false                                                        enables Java Management Extensions (JMX)
[INFO]     [creator]         $BPL_JMX_PORT                5000                                                         configure the JMX port
[INFO]     [creator]         $BPL_JVM_HEAD_ROOM           0                                                            the headroom in memory calculation
[INFO]     [creator]         $BPL_JVM_LOADED_CLASS_COUNT  35% of classes                                               the number of loaded classes in memory calculation
[INFO]     [creator]         $BPL_JVM_THREAD_COUNT        250                                                          the number of threads in memory calculation
[INFO]     [creator]         $JAVA_TOOL_OPTIONS                                                                        the JVM launch flags
[INFO]     [creator]         Using Java version 17 extracted from MANIFEST.MF
[INFO]     [creator]       BellSoft Liberica JRE 17.0.6: Contributing to layer
[INFO]     [creator]         Downloading from https://github.com/bell-sw/Liberica/releases/download/17.0.6+10/bellsoft-jre17.0.6+10-linux-amd64.tar.gz
[INFO]     [creator]         Verifying checksum
[INFO]     [creator]         Expanding to /layers/paketo-buildpacks_bellsoft-liberica/jre
[INFO]     [creator]         Adding 124 container CA certificates to JVM truststore
[INFO]     [creator]         Writing env.launch/BPI_APPLICATION_PATH.default
[INFO]     [creator]         Writing env.launch/BPI_JVM_CACERTS.default
[INFO]     [creator]         Writing env.launch/BPI_JVM_CLASS_COUNT.default
[INFO]     [creator]         Writing env.launch/BPI_JVM_SECURITY_PROVIDERS.default
[INFO]     [creator]         Writing env.launch/JAVA_HOME.default
[INFO]     [creator]         Writing env.launch/JAVA_TOOL_OPTIONS.append
[INFO]     [creator]         Writing env.launch/JAVA_TOOL_OPTIONS.delim
[INFO]     [creator]         Writing env.launch/MALLOC_ARENA_MAX.default
[INFO]     [creator]       Launch Helper: Reusing cached layer
[INFO]     [creator]       Java Security Properties: Reusing cached layer
[INFO]     [creator]     
[INFO]     [creator]     Paketo Buildpack for Syft 1.28.0
[INFO]     [creator]       https://github.com/paketo-buildpacks/syft
[INFO]     [creator]         Downloading from https://github.com/anchore/syft/releases/download/v0.77.0/syft_0.77.0_linux_amd64.tar.gz
[INFO]     [creator]         Verifying checksum
[INFO]     [creator]         Writing env.build/SYFT_CHECK_FOR_APP_UPDATE.default
[INFO]     [creator]     
[INFO]     [creator]     Paketo Buildpack for Executable JAR 6.6.3
[INFO]     [creator]       https://github.com/paketo-buildpacks/executable-jar
[INFO]     [creator]       Class Path: Contributing to layer
[INFO]     [creator]         Writing env/CLASSPATH.delim
[INFO]     [creator]         Writing env/CLASSPATH.prepend
[INFO]     [creator]       Process types:
[INFO]     [creator]         executable-jar: java org.springframework.boot.loader.JarLauncher (direct)
[INFO]     [creator]         task:           java org.springframework.boot.loader.JarLauncher (direct)
[INFO]     [creator]         web:            java org.springframework.boot.loader.JarLauncher (direct)
[INFO]     [creator]     
[INFO]     [creator]     Paketo Buildpack for Spring Boot 5.23.0
[INFO]     [creator]       https://github.com/paketo-buildpacks/spring-boot
[INFO]     [creator]       Build Configuration:
[INFO]     [creator]         $BP_SPRING_CLOUD_BINDINGS_DISABLED   false  whether to contribute Spring Boot cloud bindings support
[INFO]     [creator]       Launch Configuration:
[INFO]     [creator]         $BPL_SPRING_CLOUD_BINDINGS_DISABLED  false  whether to auto-configure Spring Boot environment properties from bindings
[INFO]     [creator]         $BPL_SPRING_CLOUD_BINDINGS_ENABLED   true   Deprecated - whether to auto-configure Spring Boot environment properties from bindings
[INFO]     [creator]       Creating slices from layers index
[INFO]     [creator]         dependencies (22.6 MB)
[INFO]     [creator]         spring-boot-loader (269.4 KB)
[INFO]     [creator]         snapshot-dependencies (0.0 B)
[INFO]     [creator]         application (37.4 KB)
[INFO]     [creator]       Launch Helper: Reusing cached layer
[INFO]     [creator]       Spring Cloud Bindings 1.11.0: Reusing cached layer
[INFO]     [creator]       Web Application Type: Reusing cached layer
[INFO]     [creator]       4 application slices
[INFO]     [creator]       Image labels:
[INFO]     [creator]         org.opencontainers.image.title
[INFO]     [creator]         org.opencontainers.image.version
[INFO]     [creator]         org.springframework.boot.version
[INFO]     [creator]     ===> EXPORTING
[INFO]     [creator]     Reusing layer 'paketo-buildpacks/ca-certificates:helper'
[INFO]     [creator]     Reusing layer 'paketo-buildpacks/bellsoft-liberica:helper'
[INFO]     [creator]     Reusing layer 'paketo-buildpacks/bellsoft-liberica:java-security-properties'
[INFO]     [creator]     Reusing layer 'paketo-buildpacks/bellsoft-liberica:jre'
[INFO]     [creator]     Reusing layer 'paketo-buildpacks/executable-jar:classpath'
[INFO]     [creator]     Reusing layer 'paketo-buildpacks/spring-boot:helper'
[INFO]     [creator]     Reusing layer 'paketo-buildpacks/spring-boot:spring-cloud-bindings'
[INFO]     [creator]     Reusing layer 'paketo-buildpacks/spring-boot:web-application-type'
[INFO]     [creator]     Reusing layer 'buildpacksio/lifecycle:launch.sbom'
[INFO]     [creator]     Reusing 5/5 app layer(s)
[INFO]     [creator]     Reusing layer 'buildpacksio/lifecycle:launcher'
[INFO]     [creator]     Reusing layer 'buildpacksio/lifecycle:config'
[INFO]     [creator]     Reusing layer 'buildpacksio/lifecycle:process-types'
[INFO]     [creator]     Adding label 'io.buildpacks.lifecycle.metadata'
[INFO]     [creator]     Adding label 'io.buildpacks.build.metadata'
[INFO]     [creator]     Adding label 'io.buildpacks.project.metadata'
[INFO]     [creator]     Adding label 'org.opencontainers.image.title'
[INFO]     [creator]     Adding label 'org.opencontainers.image.version'
[INFO]     [creator]     Adding label 'org.springframework.boot.version'
[INFO]     [creator]     Setting default process type 'web'
[INFO]     [creator]     Saving docker.io/library/demo:0.0.1-SNAPSHOT...
[INFO]     [creator]     *** Images (c6a74daeede3):
[INFO]     [creator]           docker.io/library/demo:0.0.1-SNAPSHOT
[INFO]     [creator]     Reusing cache layer 'paketo-buildpacks/syft:syft'
[INFO]     [creator]     Reusing cache layer 'buildpacksio/lifecycle:cache.sbom'
[INFO] 
[INFO] Successfully built image 'docker.io/library/demo:0.0.1-SNAPSHOT'
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  01:06 min
[INFO] Finished at: 2023-04-18T15:57:46+08:00
[INFO] ------------------------------------------------------------------------
mark-vivv@MBP demo % 

四、Docker运行测试

mark-vivv@MBP demo % docker run -p 8080:8080 demo:0.0.1-SNAPSHOT

启动日志

Setting Active Processor Count to 6
Calculating JVM memory based on 6479584K available memory
For more information on this calculation, see https://paketo.io/docs/reference/java-reference/#memory-calculator
Calculated JVM Memory Configuration: -XX:MaxDirectMemorySize=10M -Xmx6089066K -XX:MaxMetaspaceSize=83317K -XX:ReservedCodeCacheSize=240M -Xss1M (Total Memory: 6479584K, Thread Count: 50, Loaded Class Count: 12296, Headroom: 0%)
Enabling Java Native Memory Tracking
Adding 124 container CA certificates to JVM truststore
Spring Cloud Bindings Enabled
Picked up JAVA_TOOL_OPTIONS: -Djava.security.properties=/layers/paketo-buildpacks_bellsoft-liberica/java-security-properties/java-security.properties -XX:+ExitOnOutOfMemoryError -XX:ActiveProcessorCount=6 -XX:MaxDirectMemorySize=10M -Xmx6089066K -XX:MaxMetaspaceSize=83317K -XX:ReservedCodeCacheSize=240M -Xss1M -XX:+UnlockDiagnosticVMOptions -XX:NativeMemoryTracking=summary -XX:+PrintNMTStatistics -Dorg.springframework.cloud.bindings.boot.enable=true

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v3.1.0-SNAPSHOT)

2023-04-18T06:40:51.893Z  INFO 1 --- [           main] com.example.demo.DemoApplication         : Starting DemoApplication v0.0.1-SNAPSHOT using Java 17.0.6 with PID 1 (/workspace/BOOT-INF/classes started by cnb in /workspace)
2023-04-18T06:40:51.901Z  INFO 1 --- [           main] com.example.demo.DemoApplication         : No active profile set, falling back to 1 default profile: "default"
2023-04-18T06:40:53.402Z  INFO 1 --- [           main] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 1 endpoint(s) beneath base path '/actuator'
2023-04-18T06:40:53.920Z  INFO 1 --- [           main] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port 8080
2023-04-18T06:40:53.936Z  INFO 1 --- [           main] com.example.demo.DemoApplication         : Started DemoApplication in 2.415 seconds (process running for 2.92)

执行测试

mark-vivv@MBP demo % curl localhost:8080/actuator       
{
    
    "_links":{
    
    "self":{
    
    "href":"http://localhost:8080/actuator","templated":false},"health":{
    
    "href":"http://localhost:8080/actuator/health","templated":false},"health-path":{
    
    "href":"http://localhost:8080/actuator/health/{*path}","templated":true}}}%   

结束docker运行,创建kubernetes部署文件

五、执行Kubernetes部署准备

创建部署文件

mark-vivv@MBP demo % kubectl create deployment demo --image=demo:0.0.1-SNAPSHOT --dry-run=client -o=yaml > deployment.yaml
mark-vivv@MBP demo % echo "---" >> deployment.yaml
mark-vivv@MBP demo % kubectl create service clusterip demo --tcp=8080:8080 --dry-run=client -o=yaml >> deployment.yaml

注意dry-run参数,需要设定为–dry-run=client,否则会出现以下错误:

W0418 14:43:36.748209   74906 helpers.go:663] --dry-run is deprecated and can be replaced with --dry-run=client.

另外需要注意两个yaml配置文件之间需要—分隔符,完整的deployment.yaml文件内容如下

apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    app: demo
  name: demo
spec:
  replicas: 1
  selector:
    matchLabels:
      app: demo
  strategy: {
    
    }
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: demo
    spec:
      containers:
      - image: demo:0.0.1-SNAPSHOT
        name: demo
        resources: {
    
    }
status: {
    
    }
---
apiVersion: v1
kind: Service
metadata:
  creationTimestamp: null
  labels:
    app: demo
  name: demo
spec:
  ports:
  - name: 8080-8080
    port: 8080
    protocol: TCP
    targetPort: 8080
  selector:
    app: demo
  type: ClusterIP
status:
  loadBalancer: {
    
    }

执行部署

mark-vivv@MBP demo % kubectl apply -f deployment.yaml 
deployment.apps/demo created
service/demo created

检查部署情况

mark-vivv@MBP demo % kubectl get all
NAME                        READY   STATUS    RESTARTS   AGE
pod/demo-5c7c9cb5f8-nj7s6   1/1     Running   0          5s

NAME                 TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)    AGE
service/demo         ClusterIP   10.110.229.132   <none>        8080/TCP   5s
service/kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP    5h28m

NAME                   READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/demo   1/1     1            1           5s

NAME                              DESIRED   CURRENT   READY   AGE
replicaset.apps/demo-5c7c9cb5f8   1         1         1       5s

在Kubernetes内部运行的Pod是在一个私有的、隔离的网络上运行。默认情况下,它们可以从同一Kubernetes集群内的其他pod和服务中看到,但不能在该网络之外看到。当我们使用kubectl时,我们是通过一个API端点与我们的应用程序进行交互。例如:通过配置本机端口转发

mark-vivv@MBP demo % kubectl port-forward service/demo 8080:8080
Forwarding from 127.0.0.1:8080 -> 8080
Forwarding from [::1]:8080 -> 8080
Handling connection for 8080
Handling connection for 8080

或者使用kubectl创建一个proxy,将通信转发到集群范围内的私有网络。代理可以通过按control-C来终止,并且在其运行时不会显示任何输出。

mark-vivv@MBP demo % kubectl proxy

开启另一个窗口执行测试

mark-vivv@MBP demo % curl localhost:8080/actuator/health
{
    
    "status":"UP","groups":["liveness","readiness"]}% 

删除服务

kubectl delete service/demo

六、使用 Service 暴露你的应用

按照kubernetes官方说法,Service暴露应用也有多种方法,前面我们使用的是ClusterIP策略,默认只对Kubernetes集群内的节点访问,无法从Kubernetes之外的位置访问,如果需要访问,要么通过代理,要么通过端口转发的方式,为了测试方面,这里修改为NodePort方式部署应用,方便直接做测试。

尽管每个 Pod 都有一个唯一的 IP 地址,但是如果没有 Service ,这些 IP 不会暴露在集群外部。Service 允许你的应用程序接收流量。Service 也可以用在 ServiceSpec 标记type的方式暴露

  • ClusterIP (默认) - 在集群的内部 IP 上公开 Service 。这种类型使得 Service 只能从集群内访问,我们上面生成的deployment.yaml就是这种方式。
  • NodePort - 使用 NAT 在集群中每个选定 Node 的相同端口上公开 Service 。使用<NodeIP>:<NodePort> 从集群外部访问 Service。是 ClusterIP 的超集。
  • LoadBalancer - 在当前云中创建一个外部负载均衡器(如果支持的话),并为 Service 分配一个固定的外部IP。是 NodePort 的超集。
  • ExternalName - 通过返回带有该名称的 CNAME 记录,使用任意名称(由 spec 中的externalName指定)公开 Service。不使用代理。这种类型需要kube-dns的v1.7或更高版本。
mark-vivv@MBP demo % kubectl create deployment demo --image=demo:0.0.1-SNAPSHOT --dry-run=client -o=yaml > deployment.yaml
mark-vivv@MBP demo % echo "---" >> deployment.yaml
mark-vivv@MBP demo % kubectl create service nodeport demo --tcp=8080:8080 --dry-run=client -o=yaml >> deployment.yaml

最后文本差异只在 type: ClusterIP <> type: NodePort

文本比较
已产生: 2023/4/19 15:48:10

模式:  差异, 带上下文
文件: 
  - name: 8080-8080  =    - name: 8080-8080
    port: 8080              port: 8080
    protocol: TCP           protocol: TCP
    targetPort: 8080        targetPort: 8080
  selector:               selector:
    app: demo               app: demo
--------------------------------------------
  type: ClusterIP    <>   type: NodePort
--------------------------------------------
status:              =  status:
  loadBalancer: {}        loadBalancer: {}
--------------------------------------------

重新部署

mark-vivv@MBP demo % kubectl apply -f deployment.yaml 
deployment.apps/demo created
service/demo created

检查部署情况

mark-vivv@MBP demo % kubectl get all
NAME                        READY   STATUS    RESTARTS       AGE
pod/demo-5c7c9cb5f8-nj7s6   1/1     Running   1 (101m ago)   24h

NAME                 TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
service/demo         NodePort    10.103.54.238   <none>        8080:32693/TCP   11s
service/kubernetes   ClusterIP   10.96.0.1       <none>        443/TCP          30h

NAME                   READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/demo   1/1     1            1           24h

NAME                              DESIRED   CURRENT   READY   AGE
replicaset.apps/demo-5c7c9cb5f8   1         1         1       24h

注意8080:32693,本机端口是32693,映射至pod的8080端口,执行测试:

mark-vivv@MBP demo % curl localhost:32693/actuator/health
{
    
    "status":"UP","groups":["liveness","readiness"]}%    

猜你喜欢

转载自blog.csdn.net/xieshaohu/article/details/130246255