1. 创建一个本地spring-boot应用
2. 创建Dockerfile 文件
FROM adoptopenjdk:11-jre-hotspot
ADD ./target/k8s-0.0.1-SNAPSHOT.jar /hello-k8s.jar
EXPOSE 9901
ENTRYPOINT ["java","-jar","/hello-k8s.jar"]
3. 配置idea docker
前提:本地已安装好docker-desktop
4. 添加docker执行配置
5. 执行docker
下图虽然成功启动,但是没有做docker本地与docker内部端口映射,浏览器访问不通
可以通过执行以下命令解决docker run -p 127.0.0.1:9901:9901 你的image id
,然后通过浏览器即可访问你的应用
6. 此时镜像已经推送到docker-desktop上
7. 可以注册一个阿里云镜像私有仓库
cr.console.aliyun.com/ 这个是免费的
8. cmd 登陆
docker login --username=你注册的用户名 registry.cn-hangzhou.aliyuncs.com
9. 推送镜像打标到本地
docker tag hello-k8s:latest registry.cn-hangzhou.aliyuncs.com/sydml/hello-k8s:latest
将镜像推送到远程阿里云私有仓库
docker push registry.cn-hangzhou.aliyuncs.com/sydml/hello-k8s
10. 设置登陆密钥
kubectl create secret docker-registry docker-registry-secret --docker-server=registry.cn-hangzhou.aliyuncs.com --docker-username=你注册的阿里云仓库用户名 --docker-password=你的阿里云私有仓库登陆密码 --docker-email=你的邮箱
11. 登陆后将docker刚刚登陆过的认证设置到k8s
kubectl create secret generic ali-register-secret --from-file=.dockerconfigjson=C:\Users\你的用户目录\.docker\config.json --type=kubernetes.io/dockerconfigjson
12. 创建spring-boot服务yaml文件
apiVersion: v1
kind: Pod
metadata:
name: hello-k8s-pod
labels:
app: hello-k8s-pod
spec:
containers:
- name: hello-k8s-container
image: registry.cn-hangzhou.aliyuncs.com/sydml/hello-k8s
imagePullPolicy: Always
ports:
- containerPort: 9901
hostPort: 9901
restartPolicy: Always
imagePullSecrets:
- name: docker-registry-secret
如果拉取不下来,可以尝试将镜像设置为公有的
13. 执行 kubectl apply -f hello-k8s.yaml
- 重启pod
kubectl replace --force -f hello-k8s.yaml
- 删除pod
kubectl delete -n default pod hello-k8s-pod
14. 此时外网可能访问不通需要执行映射
kubectl port-forward --address 127.0.0.1 hello-k8s 9901:9901
15. 部署集群
- 启动 Deployment
kubectl apply -f k8s-dep.yaml
- 扩展副本
kubectl scale -n default deployment hello-k8s --replicas=你扩展到的数量
- 重启deployment
kubectl rollout restart -n default deployment hello-k8s
apiVersion: apps/v1
kind: Deployment
metadata:
name: hello-k8s
labels:
app: hello-k8s
spec:
replicas: 3 # 副本数量
template:
metadata:
name: hello-k8s
labels:
app: hello-k8s
env: test
spec:
containers:
- name: hello-k8s
image: registry.cn-hangzhou.aliyuncs.com/sydml/hello-k8s
imagePullPolicy: Always
ports:
- name: http-port
containerPort: 9901
imagePullSecrets:
- name: docker-registry-secret
restartPolicy: Always
selector:
matchLabels:
app: hello-k8s