Skip to content

Instantly share code, notes, and snippets.

@DavesCodeMusings
Created January 2, 2022 23:16
Show Gist options
  • Select an option

  • Save DavesCodeMusings/84f0d4ae19e8b199fed7ec077146600b to your computer and use it in GitHub Desktop.

Select an option

Save DavesCodeMusings/84f0d4ae19e8b199fed7ec077146600b to your computer and use it in GitHub Desktop.
Execute a Docker command inside a container using API calls with curl
#!/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