Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save a0xnirudh/9491f897d943454752905d2bef271389 to your computer and use it in GitHub Desktop.
Save a0xnirudh/9491f897d943454752905d2bef271389 to your computer and use it in GitHub Desktop.
Using the exec command with the docker API, and capturing output
#! /usr/bin/env bash
# Create the container with a long running process. If PID1 exists before
# we send the exec commands, they will fail because the container is not running
#
CONTAINER_NAME="TEST-`uuidgen`"
curl --silent --unix-socket /var/run/docker.sock "http:/containers/create?name=${CONTAINER_NAME}" -XPOST \
-H "Content-Type: application/json" \
-d '{
"Image": "ruby:latest",
"Cmd": [ "sleep", "10" ]
}' | jq '.'
# Start the container
#
curl --silent --unix-socket /var/run/docker.sock "http:/containers/${CONTAINER_NAME}/start" -XPOST \
-H "Content-Type: application/json" \
--output /dev/null \
--write-out "%{http_code}"
echo ""
# Create the exec
#
EXEC_CREATE=`curl --silent --unix-socket /var/run/docker.sock "http:/containers/${CONTAINER_NAME}/exec" -XPOST \
-H "Content-Type: application/json" \
-d '{
"AttachStdout": true,
"Tty": true,
"Cmd": [ "ruby", "-e", "5.times { puts :hi; sleep 1 }"]
}'
`
echo $EXEC_CREATE | jq '.'
# Run the exec
#
EXEC_ID=$(echo $EXEC_CREATE | jq -r '.Id')
curl --silent --unix-socket /var/run/docker.sock "http:/exec/${EXEC_ID}/start" -XPOST \
-H "Content-Type: application/json" \
-d '{
"Detach": false,
"Tty": true
}'
# Or use the logging API to attach to the container, and delete the JSON
# from `start`
#
# curl --silent --unix-socket /var/run/docker.sock "http:/containers/${CONTAINER_NAME}/attach?stream=1&stdout=1&stderr=1" -XPOST
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment