Skip to content

Instantly share code, notes, and snippets.

@esolitos
Created June 1, 2023 11:27
Show Gist options
  • Save esolitos/bc6fc9758430d923b2ffc90db3e057cc to your computer and use it in GitHub Desktop.
Save esolitos/bc6fc9758430d923b2ffc90db3e057cc to your computer and use it in GitHub Desktop.
Small script to get the docker command from a running container.
#!/bin/bash
# Get container name from the first script parameter
CONTAINER_NAME=$1
# Get the image name
IMAGE=$(docker inspect $CONTAINER_NAME | jq -r .[0].Config.Image)
# Get the environment variables
ENV_VARS=$(docker inspect $CONTAINER_NAME | jq -r '.[0].Config.Env[]' | sed 's/^/-e /' | tr '\n' ' ')
# Get the exposed ports
PORTS=$(docker inspect $CONTAINER_NAME | jq -r '.[0].NetworkSettings.Ports | to_entries[] | select(.value[0].HostPort != null) | "-p \(.value[0].HostPort):\(.key)"' | tr '\n' ' ')
# Get the volumes
VOLUMES=$(docker inspect $CONTAINER_NAME | jq -r '.[0].Mounts[] | select(.Type == "bind") | "-v \(.Source):\(.Destination)"' | tr '\n' ' ')
NAMED_VOLUMES=$(docker inspect $CONTAINER_NAME | jq -r '.[0].Mounts[] | select(.Type == "volume") | "-v \(.Name):\(.Destination)"' | tr '\n' ' ')
# Get the command
CMD=$(docker inspect $CONTAINER_NAME | jq -r '.[0].Config.Cmd[]' | tr '\n' ' ')
# Get the restart policy
RESTART_POLICY=$(docker inspect $CONTAINER_NAME | jq -r '.[0].HostConfig.RestartPolicy.Name' | sed 's/^/--restart /')
# Construct the docker run command
echo "docker run -d --name $CONTAINER_NAME $ENV_VARS $PORTS $VOLUMES $NAMED_VOLUMES $RESTART_POLICY $IMAGE $CMD"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment