这是坚持技术写作计划(含翻译)的第77篇,定个小目标999,每周最少2篇。
本文主要以Nocalhost工具为例,讲解如何快速开发调试跑在k8s集群的微服务等云原生应用。
安装 Nocalhost
Nocalhost 支持 VScode 和 Jetbrains (Jetbrains 插件目前不支持 2022.2.*
,提了PR 没人合,感觉 idea plugin 已经没人维护了, 我 Fork 了一个,使用 Github Action 构建了一个 2022.2.*
可用的版本 github.com/anjia0532/n…)
添加 K8S 集群
可以直接复制 kubeconfig 文本粘贴,也可以下载 kubeconfig 文件到本地
详见 集群管理
创建实例应用
官方是用 nocalhost-server 或者 istio 的 bookinfo 为例。
此处以 Java 系常用的 Spring Boot 为例。
基于 Spring Initializr 创建 demo 应用
在 com.example.nocalhostspringdemo
包下创建 Controller.java 类
package com.example.nocalhostspringdemo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author AnJia
* @since 2022-08-19 16:47
*/
@RestController("/")
public class Controller {
@GetMapping("/nocalhost-demo")
public String test() {
return "hello nocalhost";
}
}
构建 jar 包
部署应用到K8S集群
将下列 yaml 代码保存为 nocalhost-test.yaml
,执行 kubectl apply -f ./nocalhost-test.yaml
apiVersion: v1
kind: Namespace
metadata:
name: nocalhost-test
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: spring-boot-demo
namespace: nocalhost-test
labels:
app: spring-boot-demo
spec:
replicas: 3
template:
metadata:
name: spring-boot-demo
labels:
app: spring-boot-demo
spec:
containers:
- name: spring-boot-demo
image: anjia0532/openjdk-8-alpine-lib:3.5.2
imagePullPolicy: IfNotPresent
command:
- tail
- -f
- /dev/null
restartPolicy: Always
selector:
matchLabels:
app: spring-boot-demo
使用 Nocalhost 部署调试服务
在项目根目录创建个 .nocalhost
文件夹,并将下列代码保存为 config.yaml
name: "spring-boot-demo"
serviceType: "deployment"
containers:
-
name: "spring-boot-demo"
hub: null
dev:
gitUrl: ""
image: "anjia0532/openjdk-8-alpine-lib:3.5.2"
shell: "sh"
workDir: ""
storageClass: ""
resources: null
persistentVolumeDirs: []
command:
debug:
- java
- -jar
- -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005
- /home/nocalhost-dev/target/nocalhost-spring-demo-0.0.1-SNAPSHOT.jar
run:
- java
- -jar
- /home/nocalhost-dev/target/nocalhost-spring-demo-0.0.1-SNAPSHOT.jar
debug:
language: "java"
remoteDebugPort: 5005
hotReload: true
sync:
type: "sendReceive"
mode: "gitIgnore"
env: []
portForward: []
在 Controller 类里加上断点,使用远程 debug 模式启动应用。然后把8080端口转到本地。
本地浏览器访问 http://localhost:8080/nocalhost-demo 命中断点,意味着可以进行断点调试。
可以用于预发布环境下,进行调试,省去了 本地开发,提交代码,流水线构建推送镜像,发版,切换流量,看日志 的过程,生产不建议这么用,有些时候会发布失败。
另外 java 系可以结合 springboot 的热加载或者 jrebel 的热部署功能,实现修改后,不用重启,自动生效的效果。
其余Lua,JS,Python,Golang 等也都可以使用本方法。
招聘小广告
山东济南的小伙伴欢迎投简历啊 加入我们 , 一起搞事情。
长期招聘,Java程序员,大数据工程师,运维工程师,前端工程师。