分为两步:
- 制作镜像
- k8s 集群中发布 Deployment
以java后端程序为例
- 首先将程序打包
- 编写Dockerfile
- 编写app yaml
- 编写外部访问service
可以像我这样将jar包和Dockerfile放在同一个目录下
编写Dockerfile
#基础镜像,如果本地仓库没有,会从远程仓库拉取
FROM openjdk:8-jdk-alpine
#会把app.jar放在docker image的根目录下
ADD td-backup-server-0.0.1-SNAPSHOT.jar app.jar
#声明可以用这个端口
EXPOSE 8080
#指定容器启动时要执行的命令
ENTRYPOINT ["java","-jar","/app.jar"]
执行命令生成镜像
docker build -t server .
编写tdbackup.yaml
apiVersion: v1
kind: Service
metadata:
name: tdbackupserver
namespace: default
labels:
app: tdbackupserver
spec:
type: NodePort
ports:
- port: 8080
nodePort: 30090 #service对外开放端口
selector:
app: tdbackupserver
---
apiVersion: apps/v1
kind: Deployment #对象类型
metadata:
name: tdbackupserver #名称
labels:
app: tdbackupserver #标注
spec:
replicas: 2 #运行容器的副本数,修改这里可以快速修改分布式节点数量
selector:
matchLabels:
app: tdbackupserver
template:
metadata:
labels:
app: tdbackupserver
spec:
containers: #docker容器的配置
- name: tdbackupserver
image: tdbackup:latest # pull镜像的地址 ip:prot/dir/images:tag
imagePullPolicy: IfNotPresent #pull镜像时机,
ports:
- containerPort: 8080 #容器对外开放端口
暴露service
kubectl create -f tdbackup.yaml
编写mysql-pro.yaml
apiVersion: v1
kind: Service
metadata:
name: mysql-production
spec:
ports:
- port: 3306
---
kind: Endpoints
apiVersion: v1
metadata:
name: mysql-production
namespace: default
subsets:
- addresses:
- ip: 123.123.123.33
ports:
- port: 3306
修改数据库连接字符串
url: jdbc:mysql:// mysql-production:3310/tdBackupServer?useUnicode=true&characterEncoding=utf8&useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&createDatabaseIfNotExist=true
使用endpoint连接外部集群
kubectl create -f mysql-pro.yaml
任意节点ip + 30090测试 #service对外开放端口
|