以下是手动部署Java项目到Kubernetes中的实现攻略:
一、环境准备
- 安装Docker、Kubernetes、kubectl、minikube等软件
- 编写自己的Java web应用
二、创建Docker镜像
- 编写自己的Dockerfile:
```
# 基于官方的tomcat镜像构造
FROM tomcat:9-jdk11-openjdk-slim
# 定义工作目录
WORKDIR /usr/src/app
# 拷贝war包
COPY target/myapp.war /usr/local/tomcat/webapps/
```
- 构建Docker镜像:
docker build -t myapp:v1 .
三、创建Kubernetes Deployment
- 编写Deployment YAML 文件:
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp-deployment
spec:
selector:
matchLabels:
app: myapp
replicas: 2
template:
metadata:
labels:
app: myapp
spec:
containers:
- name: myapp
image: myapp:v1
ports:
- containerPort: 8080
- 使用kubectl创建Deployment:
kubectl apply -f deployment.yaml
四、创建Kubernetes Service
- 编写Service YAML 文件:
apiVersion: v1
kind: Service
metadata:
name: myapp-service
spec:
selector:
app: myapp
ports:
- protocol: TCP
port: 80
targetPort: 8080
type: NodePort
- 使用kubectl创建Service:
kubectl apply -f service.yaml
五、测试部署
- 获取minikube节点的IP:
minikube ip
- 获取myapp-service的NodePort:
kubectl get services myapp-service -o jsonpath='{.spec.ports[0].nodePort}'
- 在浏览器中访问 minikube节点IP:NodePort/yourapp
六、示例说明
-
示例一:使用Docker官方提供的Java镜像部署Hello World应用
-
编写Dockerfile:
FROM openjdk:8-jre-alpine
EXPOSE 8080
COPY app.jar /app.jar
ENTRYPOINT ["java","-jar","app.jar"] -
构建Docker镜像:
docker build -t myhello:v1 .
-
创建Deployment:
apiVersion: apps/v1
kind: Deployment
metadata:
name: myhello-deployment
spec:
selector:
matchLabels:
app: myhello
replicas: 2
template:
metadata:
labels:
app: myhello
spec:
containers:
- name: myhello
image: myhello:v1
ports:
- containerPort: 8080 -
创建Service:
apiVersion: v1
kind: Service
metadata:
name: myhello-service
spec:
selector:
app: myhello
ports:
- protocol: TCP
port: 80
targetPort: 8080
type: NodePort -
示例二:使用Spring Boot应用部署
-
编写Dockerfile:
FROM openjdk:11-jdk
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"] -
构建Docker镜像:
docker build -t myspring:v1 .
-
创建Deployment:
apiVersion: apps/v1
kind: Deployment
metadata:
name: myspring-deployment
spec:
selector:
matchLabels:
app: myspring
replicas: 2
template:
metadata:
labels:
app: myspring
spec:
containers:
- name: myspring
image: myspring:v1
ports:
- containerPort: 8080 -
创建Service:
apiVersion: v1
kind: Service
metadata:
name: myspring-service
spec:
selector:
app: myspring
ports:
- protocol: TCP
port: 80
targetPort: 8080
type: NodePort
以上就是手动部署Java应用到Kubernetes的完整攻略,希望对您有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:手动部署java项目到k8s中的实现 - Python技术站