1、java项目打成jar包

1、1 在IDEA开发工具中使用maven工具将开发完成的SpringBoot项目达成jar包

        我自己的项目生成的jar为:demojenkins.jar。

1、2 将生成jar包上传到装有docker的虚拟机上

        我上传到虚拟机的文件目录是/mydocker/springboot

1、3 编写Dockerfile文件

# Dockerfile文件内容如下:
# 基础镜像
FROM openjdk:8-jdk-alpine
VOLUME /tmp
# 将jar包添加到容器中
ADD demojenkins.jar demojenkins.jar
ENTRYPOINT ["java","-jar","/demojenkins.jar", "&"]
#暴露8111端口作为微服务
EXPOSE 8111


# Dockerfile保留字介绍:
EXPOSE:当前容器对外暴漏的端口
FROM:基础镜像,当前新镜像是基于哪个镜像的,指定一个已经存在的镜像作为模板,第一条必须是FROM
VOLUME:数据卷挂载,用于保存数据和持久化工作
ADD:将宿主机目录下的文件拷贝进镜像且会自动处理URL和解压tar压缩包
ENTRYPOINT:容器运行执行的命令,当设置了ENTRYPOINT后,docker run不会将ENTRYPOINT命令覆盖。

2、jar包制作成本地镜像

2、1 上传Dockerfile文件到/mydocker/springboot目录下

2、2 切换到/mydocker/springboot目录

$ cd /mydocker/springboot

2、3  执行docker build命令生成本地镜像:

$ docker build -t java-demo-01:1.1 .

2、4 查看镜像是否制作完成:

$ docker images java-demo-01
REPOSITORY     TAG       IMAGE ID       CREATED       SIZE
java-demo-01   1.1       160217035f51   3 hours ago   122MB

 可以看到镜像已经制作完成。

3、本地镜像生成符合阿里云镜像仓库规范的镜像

3、1 登录到阿里云官网

3、2 通过控制台找到镜像容器服务

3、3 创建一个新的镜像仓库

3、4 点击管理,进入新创建的镜像仓库中

3、5 虚拟机登录到阿里云镜像仓库

$ docker login --username=XXX registry.cn-hangzhou.aliyuncs.com

输入设置的阿里云镜像仓库密码之后即可登录成功。

3、6 生成符合阿里云镜像仓库规范的镜像

docker tag [ImageId] registry.cn-hangzhou.aliyuncs.com/glutgl/java-project-01:[镜像版本号]

 查看是否生成

$ docker images registry.cn-hangzhou.aliyuncs.com/glutgl/java-project-01
REPOSITORY                                                 TAG       IMAGE ID       CREATED       SIZE
registry.cn-hangzhou.aliyuncs.com/glutgl/java-project-01   1.1       160217035f51   3 hours ago   122MB

 可以看到已经创建成功。

4、推送到阿里云镜像仓库

$ docker push registry.cn-hangzhou.aliyuncs.com/glutgl/java-project-01:[镜像版本号]

 在阿里云容器镜像仓库中查看是否推送成功:

 可以看到镜像推送成功。

5、k8s集群创建deplyment和Pod容器

$ kubectl apply -f javademo1.yaml

# javademo1.yaml文件内容如下:
apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    app: javademo1
  name: javademo1
spec:
  replicas: 1
  selector:
    matchLabels:
      app: javademo1
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: javademo1
    spec:
      containers:
      - image: registry.cn-hangzhou.aliyuncs.com/glutgl/java-project-01:1.1
        name: java-project-01
        ports:
        - containerPort: 8111
        resources: {}
status: {}

查看deployment和Pod容器是否创建成功:

$ kubectl get deployment,pods
NAME                        READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/javademo1   1/1     1            1           88m
deployment.apps/nginx       1/1     1            1           28h

NAME                             READY   STATUS    RESTARTS   AGE
pod/javademo1-55d455d766-kd6bj   1/1     Running   0          88m
pod/nginx-f89759699-qr276        1/1     Running   1          28h

可以看到deloyment和pod已经创建成功。

6、创建service

$ kubectl apply -f javademo1-service.yaml

# javademo1-service.yaml内容如下:
apiVersion: v1
kind: Service
metadata:
  creationTimestamp: "2022-10-29T14:04:11Z"
  labels:
    app: javademo1
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:metadata:
        f:labels:
          .: {}
          f:app: {}
      f:spec:
        f:externalTrafficPolicy: {}
        f:ports:
          .: {}
          k:{"port":8111,"protocol":"TCP"}:
            .: {}
            f:port: {}
            f:protocol: {}
            f:targetPort: {}
        f:selector:
          .: {}
          f:app: {}
        f:sessionAffinity: {}
        f:type: {}
    manager: kubectl
    operation: Update
    time: "2022-10-29T14:04:11Z"
  name: javademo1
  namespace: default
  resourceVersion: "42479"
  selfLink: /api/v1/namespaces/default/services/javademo1
  uid: b7262c9a-3028-4c48-a3c9-cd11e9254adc
spec:
  clusterIP: 10.1.54.154
  externalTrafficPolicy: Cluster
  ports:
  - nodePort: 30459
    port: 8111
    protocol: TCP
    targetPort: 8111
  selector:
    app: javademo1
  sessionAffinity: None
  type: NodePort
status:
  loadBalancer: {}

 查看service:

$ kubectl get svc
NAME         TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)          AGE
javademo1    NodePort    10.1.54.154    <none>        8111:30459/TCP   89m
kubernetes   ClusterIP   10.1.0.1       <none>        443/TCP          28h

可以看到service已经创建成功。

6、使用ingress对外暴露应用

6、1 部署Ingress-Controller

$ kubectl apply -f ingress-controller.yaml

# ingress-controller.yaml文件内容如下:
apiVersion: v1
kind: Namespace
metadata:
  name: ingress-nginx
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx

---

kind: ConfigMap
apiVersion: v1
metadata:
  name: nginx-configuration
  namespace: ingress-nginx
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx

---
kind: ConfigMap
apiVersion: v1
metadata:
  name: tcp-services
  namespace: ingress-nginx
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx

---
kind: ConfigMap
apiVersion: v1
metadata:
  name: udp-services
  namespace: ingress-nginx
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx

---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: nginx-ingress-serviceaccount
  namespace: ingress-nginx
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx

---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRole
metadata:
  name: nginx-ingress-clusterrole
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
rules:
  - apiGroups:
      - ""
    resources:
      - configmaps
      - endpoints
      - nodes
      - pods
      - secrets
    verbs:
      - list
      - watch
  - apiGroups:
      - ""
    resources:
      - nodes
    verbs:
      - get
  - apiGroups:
      - ""
    resources:
      - services
    verbs:
      - get
      - list
      - watch
  - apiGroups:
      - ""
    resources:
      - events
    verbs:
      - create
      - patch
  - apiGroups:
      - "extensions"
      - "networking.k8s.io"
    resources:
      - ingresses
    verbs:
      - get
      - list
      - watch
  - apiGroups:
      - "extensions"
      - "networking.k8s.io"
    resources:
      - ingresses/status
    verbs:
      - update

---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: Role
metadata:
  name: nginx-ingress-role
  namespace: ingress-nginx
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
rules:
  - apiGroups:
      - ""
    resources:
      - configmaps
      - pods
      - secrets
      - namespaces
    verbs:
      - get
  - apiGroups:
      - ""
    resources:
      - configmaps
    resourceNames:
      # Defaults to "<election-id>-<ingress-class>"
      # Here: "<ingress-controller-leader>-<nginx>"
      # This has to be adapted if you change either parameter
      # when launching the nginx-ingress-controller.
      - "ingress-controller-leader-nginx"
    verbs:
      - get
      - update
  - apiGroups:
      - ""
    resources:
      - configmaps
    verbs:
      - create
  - apiGroups:
      - ""
    resources:
      - endpoints
    verbs:
      - get

---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: RoleBinding
metadata:
  name: nginx-ingress-role-nisa-binding
  namespace: ingress-nginx
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: nginx-ingress-role
subjects:
  - kind: ServiceAccount
    name: nginx-ingress-serviceaccount
    namespace: ingress-nginx

---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name: nginx-ingress-clusterrole-nisa-binding
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: nginx-ingress-clusterrole
subjects:
  - kind: ServiceAccount
    name: nginx-ingress-serviceaccount
    namespace: ingress-nginx

---

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-ingress-controller
  namespace: ingress-nginx
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: ingress-nginx
      app.kubernetes.io/part-of: ingress-nginx
  template:
    metadata:
      labels:
        app.kubernetes.io/name: ingress-nginx
        app.kubernetes.io/part-of: ingress-nginx
      annotations:
        prometheus.io/port: "10254"
        prometheus.io/scrape: "true"
    spec:
      hostNetwork: true
      # wait up to five minutes for the drain of connections
      terminationGracePeriodSeconds: 300
      serviceAccountName: nginx-ingress-serviceaccount
      nodeSelector:
        kubernetes.io/os: linux
      containers:
        - name: nginx-ingress-controller
          image: lizhenliang/nginx-ingress-controller:0.30.0
          args:
            - /nginx-ingress-controller
            - --configmap=$(POD_NAMESPACE)/nginx-configuration
            - --tcp-services-configmap=$(POD_NAMESPACE)/tcp-services
            - --udp-services-configmap=$(POD_NAMESPACE)/udp-services
            - --publish-service=$(POD_NAMESPACE)/ingress-nginx
            - --annotations-prefix=nginx.ingress.kubernetes.io
          securityContext:
            allowPrivilegeEscalation: true
            capabilities:
              drop:
                - ALL
              add:
                - NET_BIND_SERVICE
            # www-data -> 101
            runAsUser: 101
          env:
            - name: POD_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            - name: POD_NAMESPACE
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
          ports:
            - name: http
              containerPort: 80
              protocol: TCP
            - name: https
              containerPort: 443
              protocol: TCP
          livenessProbe:
            failureThreshold: 3
            httpGet:
              path: /healthz
              port: 10254
              scheme: HTTP
            initialDelaySeconds: 10
            periodSeconds: 10
            successThreshold: 1
            timeoutSeconds: 10
          readinessProbe:
            failureThreshold: 3
            httpGet:
              path: /healthz
              port: 10254
              scheme: HTTP
            periodSeconds: 10
            successThreshold: 1
            timeoutSeconds: 10
          lifecycle:
            preStop:
              exec:
                command:
                  - /wait-shutdown

---

apiVersion: v1
kind: LimitRange
metadata:
  name: ingress-nginx
  namespace: ingress-nginx
  labels:
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/part-of: ingress-nginx
spec:
  limits:
  - min:
      memory: 90Mi
      cpu: 100m
    type: Container

6、2 查看ingress-controller是否部署完成

查看namespace:

$ kubectl get ns
NAME              STATUS   AGE
default           Active   28h
ingress-nginx     Active   32s
kube-node-lease   Active   28h
kube-public       Active   28h
kube-system       Active   28h

查看指定ingress-controller命名空间下的pods

$ kubectl get pods -n ingress-controller
NAME                                       READY   STATUS    RESTARTS   AGE
nginx-ingress-controller-766fb9f77-fmpgp   1/1     Running   0          3m6s

 可以看到Ingress-Controller已经部署成功

6、3 创建Ingress

$ kubectl apply -f ingress.yaml

# ingress.yaml文件内容如下:
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: example-ingress
spec:
  rules:                            # ingress规则
  - host: cn.glut.ingredemo.com     # ingress访问service服务的自定义域名
    http:                           # http协议
      paths:                        # 路径列表
      - path: /user                 # 访问路径
        backend:                    # Ingress的http请求对发送到后端
          serviceName: javademo1    # 对应的后端服务名称
          servicePort: 8111         # 对应的后端服务端口号

查看ingress是否创建:

$ kubectl get ingress
NAME              CLASS    HOSTS                   ADDRESS   PORTS   AGE
example-ingress   <none>   cn.glut.ingredemo.com             80      10s

 7、在windows系统hosts文件中添加域名访问规则:

        在C:\Windows\System32\drivers\etc下找到hosts文件,修改文件权限,然后打开此文件,添加如下内容:

pod所在节点IP地址	cn.glut.ingredemo.com

8、访问Java项目

成功访问,至此k8s部署Java项目已经成功。

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐