如何通过kubectl exec让永不终止的脚本后台运行?
解决SQL Exporter在K8s Pod中后台运行及优化部署方案
一、临时解决kubectl exec卡住的问题
如果只是需要让当前命令后台运行不阻塞后续脚本,可通过以下方式修改执行命令:
- 使用
nohup结合输出重定向,让进程脱离终端并后台运行:
kubectl exec "$mssql_pod_name" -- bash -c 'nohup ./sql_exporter > /dev/null 2>&1 &'
nohup:确保进程在终端会话结束后仍能持续运行> /dev/null 2>&1:将标准输出和错误输出重定向到空设备,避免日志堆积或占用终端输出流&:将进程放到后台执行- 若需要记录进程ID方便后续管理,可将PID写入文件:
kubectl exec "$mssql_pod_name" -- bash -c 'nohup ./sql_exporter > /dev/null 2>&1 & echo $! > /tmp/sql_exporter.pid'
二、更优的K8s部署方案:Sidecar容器
在Pod内手动安装插件并非K8s的最佳实践,推荐使用Sidecar容器部署sql_exporter,具体方案如下:
- 修改MSSQL的Deployment配置,新增一个sql_exporter的Sidecar容器:
- 直接使用sql_exporter的官方镜像(或自行构建包含配置文件的自定义镜像)
- 通过ConfigMap挂载
sql_exporter.yml和mssql_standard.collector.yml配置文件到容器内指定路径 - 配置容器启动命令,指定配置文件路径
- 示例Deployment片段:
apiVersion: apps/v1 kind: Deployment metadata: name: mssql-deployment spec: replicas: 1 selector: matchLabels: app: mssql template: metadata: labels: app: mssql spec: containers: - name: mssql image: mcr.microsoft.com/mssql/server:latest # 省略MSSQL的环境变量、存储等配置 - name: sql-exporter image: prometheuscommunity/sql-exporter:latest args: - "--config.file=/etc/sql_exporter/sql_exporter.yml" volumeMounts: - name: sql-exporter-config mountPath: /etc/sql_exporter volumes: - name: sql-exporter-config configMap: name: sql-exporter-config
- 对应的ConfigMap配置示例:
apiVersion: v1 kind: ConfigMap metadata: name: sql-exporter-config data: sql_exporter.yml: | # 填写你的sql_exporter配置内容 mssql_standard.collector.yml: | # 填写标准MSSQL采集器的配置内容
Sidecar方案的优势
- 与主容器(MSSQL)解耦,各自拥有独立生命周期,升级或重启sql_exporter不会影响MSSQL服务
- 配置通过ConfigMap管理,修改后无需重新构建镜像,直接更新ConfigMap即可生效
- 共享Pod的网络命名空间,sql_exporter可直接通过
localhost访问MSSQL服务,无需额外配置网络 - 符合K8s声明式部署理念,便于版本控制和批量管理
内容的提问来源于stack exchange,提问作者bZhang
相关产品推荐
相关产品推荐

