Kubernetes 部署应用
准备
创建项目
1 2 3 4 5 6 7 8 9
| @RestController class HelloController {
@GetMapping("/") fun index() = "docker-demo index!"
@GetMapping("/hello") fun hello(@RequestParam name: String) = "hello ${name}!" }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <plugin> <groupId>com.spotify</groupId> <artifactId>dockerfile-maven-plugin</artifactId> <version>${dockerfile-maven-plugin.version}</version> <executions> <execution> <id>default</id> <goals> <goal>build</goal> <goal>push</goal> </goals> </execution> </executions> <configuration> <repository>chenkaixin12121/${project.artifactId}</repository> <tag>${project.version}</tag> <buildArgs> <JAR_FILE>${project.build.finalName}.jar</JAR_FILE> </buildArgs> </configuration> </plugin>
|
1 2 3 4 5 6
| FROM eclipse-temurin:17-jre-jammy LABEL authors="chenkaixin12121" VOLUME /tmp COPY target/*.jar docker-demo.jar ENTRYPOINT ["java", "-jar", "/docker-demo.jar"] EXPOSE 8080
|
构建镜像
1 2 3 4 5
| # 打包并构建镜像 maven clean package
# 推送 docker push chenkaixin12121/docker-demo:0.0.1-SNAPSHOT
|
部署
Deployment 文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| apiVersion: v1 kind: Namespace metadata: name: my-namespace
---
apiVersion: apps/v1 kind: Deployment metadata: name: docker-demo namespace: my-namespace spec: replicas: 2 selector: matchLabels: name: docker-demo template: metadata: labels: name: docker-demo spec: containers: - name: docker-demo image: chenkaixin12121/docker-demo:0.0.1-SNAPSHOT imagePullPolicy: IfNotPresent ports: - containerPort: 8080
---
apiVersion: v1 kind: Service metadata: name: docker-demo namespace: my-namespace spec:
type: LoadBalancer selector: name: docker-demo ports: - name: http protocol: TCP port: 8080 targetPort: 8080
|
部署应用
1 2 3 4 5
| # 部署 kubectl apply -f deployment.yaml
# 查看 kubectl get po,svc,deploy -o wide -n my-namespace
|
访问 http://localhost:8080/ , http://localhost:8080/hello?name=chenkaixin12121
常用命令
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| -o wide yaml json -n NAMESPACE_NAME
# 查看 kubectl get namespace kubectl get deploy kubectl get po kubectl get svc
# 删除 kubectl delete -f deployment.yaml kubectl delete namespace NAMESPACE_NAME kubectl delete deploy DEPLOYMENT_NAME kubectl delete po POD_NAME # 删除后自动增加 pod kubectl delete svc SERVICE_NAME
# 服务扩容 kubectl scale deploy DEPLOYMENT_NAME --replicas=3 # 自动扩容 kubectl autoscale deploy DEPLOYMENT_NAME --min=1 --max=4
# 设置默认 namespace kubectl config set-context --current --namespace=NAMESPACE_NAME
# 查看日志 kubectl logs -f POD_NAME
|