使用K8S部署应用程序

在这里插入图片描述
img

img

创建一个名为 nginx-deployment.yml 文件:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  namespace: webapp
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:alpine
        ports:
        - containerPort: 80

在该YAML文件中,定义了需要创建的资源类型为 Deployment,在 metadata 中声明了该 Deployment的 名称以及标签。spec 中则定义了该 Deployment 的具体设置,通过 replicas 定义了该 Deployment 创建后将会自动创建 3 个 Pod 实例。运行的 Pod 以及进行则通过 template 进行定义

# 创建 namespace
kubectl create ns <namespace>

kubectl create -f nginx-deployment.yml

image-20240326153050944

这里提示镜像拉去失败,重新换了 nginx 镜像版本后成功启动,使用 describe 命令查看 pod 运行状态

kubectl describe pod nginx-deployment-f7ccf9478-ffrvj -n webapp

通过 kubectl get 命令查看当前 Deployment 的部署进度:

# 查看Deployment的运行状态
$ kubectl get deployments

为了能够让用户或者其它服务能够访问到 Nginx 实例,这里通过一个名为 nginx-service.yml 的文件定义 Service 资源:

# 部署时删除注释
apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  type: NodePort            // 配置NodePort,外部流量可访问k8s中的服务
  ports:
  - port: 30080             // 服务访问端口,集群内部访问的端口
    targetPort: 80          // pod 控制器中定义的端口(应用访问的端口)
    nodePort: 30002         // NodePort,外部客户端访问的端口
  selector:
    name: nginx-pod

默认情况下,Service 资源只能通过集群网络进行访问 (type=ClusterIP)。这里为了能够直接访问该 Service,需要将容器端口映射到主机上,因此定义该 Service 类型为 NodePort

kubectl create -f nginx-service.yml
kubectl get svc

image-20240326160154102

其他命令:

# 部署完成后,如果需要对Nginx实例进行扩展,可以使用
kubectl scale deployments/nginx-deployment --replicas=4
# 对镜像进行滚动升级
kubectl set image deployment/nginx-deployment nginx=nginx:1.9.1
# 如果升级后服务出现异常,那么可以通过以下命令对应用进行回滚
kubectl rollout undo deployment/nginx-deployment

相关推荐

  1. k8s Ingress部署应用

    2024-03-28 04:26:01       33 阅读
  2. k8s使用yml文件部署

    2024-03-28 04:26:01       8 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-28 04:26:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-28 04:26:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-28 04:26:01       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-28 04:26:01       20 阅读

热门阅读

  1. typeScript6(其他类型)

    2024-03-28 04:26:01       16 阅读
  2. git的实际应用场景

    2024-03-28 04:26:01       18 阅读
  3. Docker的常用命令

    2024-03-28 04:26:01       17 阅读
  4. 数据分析---SQL基础

    2024-03-28 04:26:01       20 阅读
  5. 失业我们要直面恐惧乐观应对,早做准备和计划

    2024-03-28 04:26:01       18 阅读
  6. SSRF漏洞

    2024-03-28 04:26:01       18 阅读
  7. FAST-LIO2代码解析(一)

    2024-03-28 04:26:01       21 阅读
  8. codeforces - 1703 - D - Double String (字符串)

    2024-03-28 04:26:01       17 阅读
  9. 2024年通信安全员考试真题题库

    2024-03-28 04:26:01       17 阅读
  10. vs code

    vs code

    2024-03-28 04:26:01      21 阅读
  11. Android中的有序广播与无序广播

    2024-03-28 04:26:01       19 阅读