Murugaraju Perumalla
Murugaraju Perumalla

Reputation: 435

How to use Docker api engine to exec cmd in container

How to use Docker api engine to exec command in container. I want to use the api docker to exec cmds in container via http calls

Upvotes: 3

Views: 3177

Answers (1)

Murugaraju Perumalla
Murugaraju Perumalla

Reputation: 435

If you want to do exec the cmd in container you need to enter either id or name of the container, here the id is not similar to which we will get to see by executing docker ps -a, there is one EndPoint to fetch details in json of running containers i.e. enter image description here

The result response as shown below

{
    "Id": "ba7b20038dfe49d326788258eca42acb752405db835e09ffdf2705fdc16b7d17",
    "Names": [
        "/muruga"
    ],
    "Image": "ubuntu",
    "ImageID": "sha256:93fd78260bd1495afb484371928661f63e64be306b7ac48e2d13ce9422dfee26",
    "Command": "/bin/bash",
    "Created": 1544778203,
    "Ports": [],
    "Labels": {},
    "State": "running",
    "Status": "Up 3 seconds",
    "HostConfig": {
        "NetworkMode": "default"
    },
    "NetworkSettings": {
        "Networks": {
            "bridge": {
                "IPAMConfig": null,
                "Links": null,
                "Aliases": null,
                "NetworkID": "6204f5fc4d3689aebe589bd1eab4a94f73a249d69aa88772a800d94f1edc1ea6",
                "EndpointID": "7509759b07f6463b4a0a88baa00a5f6834cf69615ac88bb8bc1dbd8557be7db3",
                "Gateway": "172.17.0.1",
                "IPAddress": "172.17.0.2",
                "IPPrefixLen": 16,
                "IPv6Gateway": "",
                "GlobalIPv6Address": "",
                "GlobalIPv6PrefixLen": 0,
                "MacAddress": "02:42:ac:11:00:02",
                "DriverOpts": null
            }
        }
    },
    "Mounts": []
}

You need to use either id or name of the running container to create 'exec' instance i.e. url===>Post /containers/{{id/name}}/exec

`Post data

 {
"AttachStdin": true,
"AttachStdout": true,
"AttachStderr": true,
"DetachKeys": "ctrl-p,ctrl-q",
"Tty": true,
"Cmd": [
"bin/bash","-c","touch appa.py"
],
"Env": [
"FOO=bar",
"BAZ=quux"
],
"Privileged":true,
"User":"root"
}`

enter image description here

it returns the response 201 with json id, this id is unique every time exec instance post done it will return unique id, you need to copy this id and pass it to another url or endpoin

url===>post /exec/{{id(unique id which I mentioned in above from response)}}/start post with following data

{
  "Detach": true,
  "Tty": false
}

it returns with 200 ok, you can get into container and check the execution of the commands

enter image description here

Upvotes: 4

Related Questions