无法在 pod 内发送 http post 请求

时间:2021-07-30 15:50:53

标签: docker post docker-compose dockerfile docker-container

这是我的 go 程序,用于列出集群中运行的所有违反约束的情况。在 vscode 中手动运行这个程序给我这个输出

包主

   import (
        "bytes"
        "encoding/json"
        "flag"
        "log"
        "net/http"
    
        "github.com/vikiatinvisiblio/opa/pkg/opa"
    )
    
    var (
        inCluster = flag.Bool("incluster", false,
            "Does the exporter run within a K8S cluster, when true it will try to look for K8S service account details in the usual location.")
    )
    
    func main() {
        constraints, err := opa.GetConstraints(inCluster)
        if err != nil {
            log.Printf("err: %+v\n", err)
        }
        log.Println("listing constraints violations...")
        jsondata, err := json.MarshalIndent(constraints, "", "") //remove spacing in this line
        if err != nil {
            log.Printf("err: %+v\n", err)
        }
        log.Printf("data: %v", string(jsondata))
        //sendRequest("request check")
        sendRequest(string(jsondata))
        log.Print("request sent")
    
    }
    func sendRequest(data string) error {
        buff := bytes.NewBuffer([]byte(data))
        req, err := http.NewRequest(http.MethodPost, "https://1c986ki7lb.execute-api.us-east-1.amazonaws.com/dev", buff)
        if err != nil {
            log.Print("httprequesterror ", err)
            return err
        }
        client := &http.Client{}
        resp, err := client.Do(req)
        if err != nil {
            log.Print("httpresponseerror", err)
            return err
        }
        log.Println(resp.Status)
        return nil
    }

输出

"Meta": {
"Kind": "K8sBlockNodePort",
"Name": "block-node-port"
},
"Spec": {
"enforcementAction": ""
},
"Status": {
"totalViolations": 0,
"Violations": null,
"audittimestamp": "2021-07-30T15:22:56Z"
}
}
]
2021/07/30 20:53:53 200 OK
2021/07/30 20:53:53 request sent

此处显示约束违规并将输出发送到 api 端点。

但是当我尝试构建一个 docker 镜像并尝试在 pod 中运行它时,我得到如下输出

{
"Cluster": {
"clustername": "minikube-sathya"
},
"Meta": {
"Kind": "K8sBlockNodePort",
"Name": "block-node-port"
},
"Spec": {
"enforcementAction": ""
},
"Status": {
"totalViolations": 0,
"Violations": null,
"audittimestamp": "2021-07-30T15:06:56Z"
}
}
]

它在单独显示违规后停止。它没有将请求发送到 api。我尝试使用日志语句,但我无法解决这个问题。

0 个答案:

没有答案