项目环境搭建【Docker+k8s】九 || kubernetes创建容器

目录

创建容器

命令中--replicas=2 启动2个实例,--port=80 运行在k8s的80端口上,没有进行映射端口

[ ~]# kubectl run nginx --image=nginx --replicas=2 --port=80
#输出如下:
kubectl run --generator=deployment/apps.v1 is DEPRECATED and will be removed in a future version. Use kubectl run --generator=run-pod/v1 or kubectl create instead.
deployment.apps/nginx created

查看全部Pods状态

[ ~]# kubectl get pods
#输出如下:
NAME                     READY   STATUS    RESTARTS   AGE
nginx-5578584966-2tkmz   1/1     Running   0          79s
nginx-5578584966-8r8jt   1/1     Running   0          79s

查看已部署的服务

[ ~]# kubectl get deployment
#输出如下:
NAME    READY   UP-TO-DATE   AVAILABLE   AGE
nginx   2/2     2            2           2m17s

发布服务

使用负载均衡模式发布服务,让用户可以访问。暴露一个名称为nginx的deployment,暴露80端口,类型是负载均衡

[ ~]# kubectl expose deployment nginx --port=80 --type=LoadBalancer
#输出如下:
service/nginx exposed

查看已发布的服务

[ ~]# kubectl get service
#输出如下
NAME         TYPE           CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE
kubernetes   ClusterIP      10.96.0.1      <none>        443/TCP        9h
nginx        LoadBalancer   10.106.9.160   <pending>     80:31176/TCP   2m9s

其中nginx的port:80为k8s的端口,31176为暴露出来的端口

查看服务详情

[ ~]# kubectl get service
#输出如下
NAME         TYPE           CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE
kubernetes   ClusterIP      10.96.0.1      <none>        443/TCP        9h
nginx        LoadBalancer   10.106.9.160   <pending>     80:31176/TCP   2m9s
#查看详情
[ ~]# kubectl describe service nginx
Name:                     nginx
Namespace:                default
Labels:                   run=nginx
Annotations:              <none>
Selector:                 run=nginx
Type:                     LoadBalancer
IP:                       10.106.9.160 #k8s内部ip地址
Port:                     <unset>  80/TCP #k8s内部端口
TargetPort:               80/TCP
NodePort:                 <unset>  31176/TCP #node端口
Endpoints:                192.168.114.193:80,192.168.170.4:80
Session Affinity:         None
External Traffic Policy:  Cluster
Events:                   <none>

验证是否成功

master在默认情况下不会运行pod,所以在node节点访问nginx进行验证,也可使用docker ps查看运行的容器。

服务高可用测试:使用docker rm -f 容器id删除容器,删除后容器又自动创建。

#访问测试
http://192.168.101.31:31176/
http://192.168.101.32:31176/

停止服务

  • service是服务,对外提供服务
  • deployment是部署
  • pod运行容器的单元

容器运行在pod上,pod运行在deployment上,停止服务,必须先停止deployment

删除已部署的服务

[ ~]# kubectl delete deployment nginx
#输出如下:
deployment.apps "nginx" deleted

删除已发布的服务

[ ~]# kubectl delete service nginx
#输出如下:
service "nginx" deleted

相关推荐