目标

封装一个socat命令,实现开机自启,对6443端口进行转发,代理对k8s api server的请求

实现

定义systemd unit:vim /lib/systemd/system/socat.service

[Unit]
Description=socat port-forwarding 6443
After=network.target

[Service]
Type=forking
ExecStart=/bin/port-forwarding-start.sh
ExecStop=/bin/port-forwarding-stop.sh
Environment="PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/usr/local/git/bin"

[Install]
WantedBy=multi-user.target

port-forwarding-start.sh

#!/bin/bash

nohup socat TCP-LISTEN:6443,reuseaddr,fork TCP:192.168.2.5:6443 >> /var/log/socat.log 2>&1 &

port-forwarding-stop.sh

#!/usr/bin/env bash

pgrep socat | xargs kill -9

注意事项

最初定义start和stop脚本时,将脚本放到了/root下的子目录里,发现systemctl start socat总是会报No such file or directory错误。经过搜索,有回答说是systemd启动阶段里,脚本所在的目录还未被mount,所以会有No such file or directory错误。最终将脚本放到了/bin目录下发现可以正常启动。

systemd的多阶段细节有待深入了解。

参考

linux - Failed at step EXEC spawning: No such file or directory - Super User

文章目录