Created
January 2, 2022 23:16
-
-
Save DavesCodeMusings/84f0d4ae19e8b199fed7ec077146600b to your computer and use it in GitHub Desktop.
Execute a Docker command inside a container using API calls with curl
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # Docker API Exec proof of concept. Run a `date` command in a container with curl. | |
| echo "Choose a container ID (or CTRL+C to exit)" | |
| CONTAINER_ID_LIST=$(curl --unix-socket /var/run/docker.sock http://localhost/containers/json 2>/dev/null | jq -r .[].Id) | |
| select CONTAINER_ID in $CONTAINER_ID_LIST; do | |
| # Create an exec instance and retain the ID that was returned. | |
| EXEC_ID=$(curl -s \ | |
| --unix-socket /var/run/docker.sock \ | |
| -X POST http://localhost/containers/${CONTAINER_ID}/exec \ | |
| -H 'Content-Type: application/json' \ | |
| --data '{ "Tty": true, "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "Cmd": [ "date", "--iso-8601=seconds" ] }' \ | |
| | jq -r .Id) | |
| # Run the exec instance using the ID from the previous step. | |
| OUTPUT=$(curl -s \ | |
| --unix-socket /var/run/docker.sock \ | |
| -X POST http://localhost/exec/${EXEC_ID}/start \ | |
| -H 'Content-Type: application/json' \ | |
| --data '{ "Detach": false, "Tty": true }') | |
| # Display the command output. | |
| echo $OUTPUT | |
| done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment