Last active
May 8, 2025 20:31
-
-
Save thimslugga/957c0ff8b252b838bfe37a67803d4402 to your computer and use it in GitHub Desktop.
Get docker run for a container name or ID
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 | |
set -euo pipefail | |
# ./get_docker_run.sh c56975e847b4 | |
# docker run -d -e "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" -v /root:/data public.ecr.aws/docker/library/amazonlinux:2023 /bin/bash | |
if [[ "$#" -ne 1 ]]; then | |
echo "Usage: $0 <container_name_or_id>" | |
exit 1 | |
fi | |
container="$1" | |
docker_inspect="$(docker inspect $container)" | |
image="$(echo $docker_inspect | jq -r '.[0].Config.Image')" | |
entrypoint="$(echo $docker_inspect | jq -r '.[0].Config.Entrypoint[]?' 2>/dev/null | tr '\n' ' ' | sed 's/ $//')" | |
entrypoint_cmd="" | |
[[ -n "$entrypoint" ]] && entrypoint_cmd="--entrypoint=\"$entrypoint\" " | |
cmd="$(echo $docker_inspect | jq -r '.[0].Config.Cmd[]?' 2>/dev/null | tr '\n' ' ' | sed 's/ $//')" | |
cmd_str="" | |
[[ -n "$cmd" ]] && cmd_str="$cmd" | |
env_vars="$(echo $docker_inspect | jq -r '.[0].Config.Env[]?' 2>/dev/null | awk '{print "-e \""$0"\""}' | tr '\n' ' ')" | |
volumes="$(echo $docker_inspect | jq -r '.[0].HostConfig.Binds[]?' 2>/dev/null | awk '{print "-v "$0}' | tr '\n' ' ')" | |
ports="$(echo $docker_inspect | jq -r '.[0].HostConfig.PortBindings | keys[]?' 2>/dev/null | \ | |
xargs -I{} bash -c "echo $docker_inspect | \ | |
jq -r '.[0].HostConfig.PortBindings.\"{}\"[0].HostPort + \":{}\"'" | \ | |
awk '{print "-p "$0}' | tr '\n' ' ')" | |
echo "docker run -d $entrypoint_cmd$env_vars$volumes$ports $image $cmd_str" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment