簡體   English   中英

從Nodejs訪問kubernetes集群API

[英]Access kubernetes cluster API from Nodejs

我有一個從 Create React App 搭建的客戶端反應應用程序。 這部署在 Kubernetes 集群中並暴露於互聯網。

現在,我想從這個 API 訪問 REST API。 這個 REST API 部署到同一個集群,但只暴露給集群(而不是互聯網)。

我的問題是,如果我為我的客戶端反應應用程序添加 Nodejs 服務器層並部署到同一個集群,我是否能夠訪問 REST API 而不會暴露在互聯網上?

或者,我應該將 go 暴露在互聯網上嗎?

不確定我是否完全按照。 但是,您可以從部署在 POD 中的 node.js 服務器訪問 k8s API,它將獲得與 POD 相同的權限。

I have something similar to this, an express application running in the pod that provides a REST API for a REACT app, calling the REST API looks up the specific k8s API I need for the APP. 我們經常使用 NodeRed 對這些 REST -> k8sAPI 進行原型制作。

希望這會有所幫助,下面是一個示例。 (完全披露,黑客不是程序員;-)

例子....

const axios = require("axios");
const k8s = require("@kubernetes/client-node");


const kc = new k8s.KubeConfig();
kc.loadFromDefault();


async function getnskey(user) {
//Match username from gitlab with ns-map/namespace key and return   
    const k8sApi = kc.makeApiClient(k8s.CoreV1Api);

    const response = await k8sApi.readNamespacedConfigMap('ns-map', 'epicmgrsrv')

    let userns;
    
    let userlist = response.body.data;

    if ( userlist.hasOwnProperty(user)) {
        userns = userlist[user];
    }

    const response2 = await k8sApi.readNamespacedSecret('mgrsrvkey', userns)

    //let key = Buffer.from(response2.body.data["key"], 'base64').toString();

    const nskey = {
        userns: userns,
        nskey: response2.body.data["key"],
    };

    return nskey;
}

app.get("/user", (req, res) => {
    console.log("getting user data!");
//    console.log(JSON.stringify(req.headers));


    if (typeof(req.headers.authorization) !== undefined && req.headers.authorization.length > 10 ) {
        axios.get("https://api.github.com/user" , {
            headers: {
                Authorization: req.headers.authorization,
            },
        }).then((response) => {
            getnskey(response.data.login)
            .then(nskey => {

                const user = {
                    name: response.data.login,
                    userns: nskey.userns,
                    nskey: nskey.nskey,
                }
                console.log(user);
                res.send(user)
            })
        });
    } else {
        console.log("no authorization");
    }


    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM