Bash命令大体可以分为两类: 第一类是可执行文件,例如ls等 第二类是Bash内建命令,常见echo,cd等
执行容器的命令exec
exec命令同样类似于docker的exec命令,为在一个已经运行的容器中执行一条shell命令,如果一个pod容器中,有多个容器,需要使用-c选项指定容器。
执行Pod的data命令,默认是用Pod中的第一个容器执行
kubectl exec <pod-name> data
指定Pod中某个容器执行data命令
kubectl exec <pod-name> -c <container-name> data
通过bash获得Pod中某个容器的TTY,相当于登录容器
kubectl exec -it <pod-name> -c <container-name> bash
格式如下
#kubectl exec -it podName -c containerName -n namespace -- shell comand
###如果不设置containerName则默认是第一个containerName
###注意:
shell命令前,要加-- 号,不然shell命令中的参数,不能识别
通过bash获得pod中某个容器的TTY,相当于登录容器
#kubectl exec -it <pod-name> -n <name-space> bash
1、命令行,创建一个test文件:
#kubectl exec -it <podname> -c <container name> -n <namespace> \
-- touch /usr/local/test
2、创建目录
#kubectl exec -it spark-master-xksl -c spark-master -n spark -- mkdir -p /usr/local/spark
3、执行bash可执行文件
#kubectl exec nginx-6b6db56874-67pf4 -n prod -- 'ls'
client_body_temp
conf
fastcgi_temp
html
logs
proxy_temp
sbin
scgi_temp
uwsgi_temp
4、执行bash内建命令,或者其他的命令
#kubectl exec nginx-6b6db56874-67pf4 -n prod -- bash -c 'df -h'
Filesystem Size Used Avail Use% Mounted on
overlay 296G 58G 226G 21% /
tmpfs 64M 0 64M 0% /dev
tmpfs 7.5G 0 7.5G 0% /sys/fs/cgroup
/dev/vda1 296G 58G 226G 21% /usr/share/zoneinfo/UTC
#kubectl exec nginx-6b6db56874-67pf4 -n prod -- bash -c '/home/dayiops/nginx/sbin/nginx -t'
nginx: the configuration file /home/dayiops/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /home/dayiops/nginx/conf/nginx.conf test is successful
5、root切换普通用户执行bash内建命令,或者其他的命令
#su devopsadmin -c "kubectl exec nginx-6b6db56874-67pf4 -n prod -- bash -c '/home/dayiops/nginx/sbin/nginx -t'"
nginx: the configuration file /home/dayiops/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /home/dayiops/nginx/conf/nginx.conf test is successful
#su devopsadmin -c "kubectl exec nginx-6b6db56874-67pf4 -n prod -- bash -c '/home/dayiops/nginx/sbin/nginx -s reload'"
另外这个文章写的比较蛮不错的(推荐看看)