问题
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