Docker API NodeJS

坚强是说给别人听的谎言 提交于 2021-01-29 04:01:14

问题


I'm using the nodeJS request library to call a unix domain socket, specifically the Docker API. This works fine and returns a list of containers.

curl --unix-socket /var/run/docker.sock http:/v1.24/containers/json

However, this returns a 400400 Bad Request and I'm not sure why

var request = require('request');
request('http://unix:/var/run/docker.sock:http:/v1.24/containers/json', headers="Content-Type': 'application/json" , function (error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body)
    } else {
        console.log("Response: " + response.statusCode + body)
    }

});

回答1:


Make sure you mount the docker socket when you run the container i.e

docker run --name containera \
  -v /var/run/docker.sock:/var/run/docker.sock \
  yourimage

Give this a shot to list your containers:

        let options = {
          socketPath: '/var/run/docker.sock',
          path: `/v1.26/containers/json`,
          method: 'GET'
        };
        let clientRequest = http.request(options, (res) => {
            res.setEncoding('utf8');
            let rawData = '';
            res.on('data', (chunk) => {
                rawData += chunk; 
            });
            res.on('end', () => {
                const parsedData = JSON.parse(rawData);
                console.log(parsedData);

            });
        });
        clientRequest.on('error', (e) => {
            console.log(e);
        });
        clientRequest.end();



回答2:


While this can be done with request I would consider using Dockerode the Node SDK for Docker API as it handles the headers correctly and avoids issues like 400 Bad Request. Here is the NPM Link Dockerode NPMJS



来源:https://stackoverflow.com/questions/42114992/docker-api-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!