一. 创建Redis的deployment和service
1. 创建Redis deployment
redis-master-deployment.yaml
apiVersion: apps/v1 # for versions before 1.9. use apps/v1beta2
kind: Deployment
metadata:
name: redis-master
labels:
app: redis
spec:
selector:
matchLabels:
app: redis
role: master
tier: backend
replicas:
template:
metadata:
labels:
app: redis
role: master
tier: backend
spec:
containers:
- name: master
image: k8s.gcr.io/redis:e2e # or just image: redis
resources:
requests:
cpu: 100m
memory: 100Mi
ports:
- containerPort:
执行:
kubectl create -f redis-master-deployment.yaml
查看执行结果:
deployment "redis-master" created
当 pod 是 ready 时,将得到: kubectl get pods NAME READY STATUS RESTARTS AGE
redis-master-765d459796-258hz / Running 50s kubectl get deployment NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE
redis-master 55s kubectl get rs NAME DESIRED CURRENT READY AGE
redis-master-765d459796 1m
2. 创建redis service
redis-master-service.yaml
apiVersion: v1
kind: Service
metadata:
name: redis-master
labels:
app: redis
role: master
tier: backend
spec:
ports:
- port:
targetPort:
selector:
app: redis
role: master
tier: backend
执行:
kubectl create -f redis-master-service.yaml
查看结果:
service "redis-master" created
3. 验证 Redis 服务是否运行在 pod 中并且监听 6379 端口:
kubectl get pods redis-master-765d459796-258hz –template=‘{{(index (index .spec.containers ).ports ).containerPort}}{{”\n”}}’
输出:
二、转发一个本地端口到Pod端口
1. 从 Kubernetes v1.10 开始,kubectl port-forward
允许使用资源名称(例如服务名称)来选择匹配的 pod 来进行端口转发。
kubectl port-forward redis-master-765d459796-258hz :
相当于:
kubectl port-forward pods/redis-master-765d459796-258hz :
或
kubectl port-forward deployment/redis-master :
或
kubectl port-forward rs/redis-master :
或
kubectl port-forward svc/redis-master :
以上的命令都有效,输出类似于:
I0710 ::38.274550 portforward.go:] Forwarding from 127.0.0.1: ->
I0710 ::38.274797 portforward.go:] Forwarding from [::]: ->
2. 启动 Redis 命令行接口:
redis-cli
在 Redis 命令行提示符下,输入 ping
命令:
127.0.0.1:>ping
提示ping成功
与本地 6379 端口建立的连接将转发到运行 Redis 服务器的 pod 的 6379 端口。通过此连接,可以使用本地工作站来调试在 pod 中运行的数据库。