Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 654
Murugaraju Perumalla Avatar asked Dec 08 '25 06:12

Murugaraju Perumalla


1 Answers

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

like image 53
Murugaraju Perumalla Avatar answered Dec 12 '25 13:12

Murugaraju Perumalla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!