Skip to content

Instantly share code, notes, and snippets.

@akkerman
Last active November 20, 2024 12:16
Show Gist options
  • Select an option

  • Save akkerman/b530c0ee3906c369175991c0a13b3612 to your computer and use it in GitHub Desktop.

Select an option

Save akkerman/b530c0ee3906c369175991c0a13b3612 to your computer and use it in GitHub Desktop.
docker custom commands
# Description: Custom docker commands
# Usage: docker <command> <args>
#
# docker ip <container_name> - Get the IP address of a container
# docker env <container_name> - Get the environment variables of a container
# docker labels <container_name> - Get the labels of a container
# docker id <container_name> - Get the ID of a container
#
# docker name inspect <container_name> - Inspect a container by name
# docker name ip <container_name> - Get the IP address of a container by name
#
# docker image labels <image_name> - Get the labels of an image
#
# docker service env <service_name> - Get the environment variables of a service
# docker service labels <service_name> - Get the labels of a service
# docker service ps - List all running services with their nodes, names and images
function docker() {
case "$1" in
ip)
command docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "${@:2}"
;;
env)
command docker inspect --format '{{json .Config.Env}}' "${@:2}" | jq
;;
labels)
command docker inspect --format='{{json .Config.Labels}}' "${@:2}" | jq
;;
id)
command docker ps -f "name=$2" --format "{{.ID}}"
;;
name)
case "$2" in
inspect)
command docker inspect $(docker id $3)
;;
ip)
docker ip $(docker id $3)
;;
*)
command docker "$@"
;;
esac
;;
image)
if [ "$2" = labels ]; then
command docker image inspect -f "{{json .Config.Labels}}" "${@:3}" | jq
else
command docker "$@"
fi
;;
service)
if [ "$2" = env ]; then
command docker service inspect -f "{{json .Spec.TaskTemplate.ContainerSpec.Env}}" "${@:3}" | jq
elif [ "$2" = labels ]; then
command docker service inspect -f "{{json .Spec.Labels}}" "${@:3}" | jq
elif [ "$2" = ps ]; then
for name in $(command docker stack ls --format '{{.Name}}'); do
command docker stack ps $name --filter="desired-state=running" --format '{{.Node}}\t{{.Name}}\t{{.Image}}'
done | sort | column -t
else
command docker "$@"
fi
;;
*)
command docker "$@"
;;
esac
}
@akkerman
Copy link
Copy Markdown
Author

Source this file from bashrc or zshrc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment