Last active
December 18, 2023 10:42
-
-
Save Attumm/81bcf764ec12e633a54c59a00af3c70c to your computer and use it in GitHub Desktop.
Running docker in production will eventually lead to the question: "How was this instance initially started". This script tries recreate the initial docker run command from docker config.
This file contains 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 | |
if (( $# != 1 )); then | |
echo "Error: No Docker container ID provided." | |
exit 1 | |
fi | |
CONTAINER_ID=$1 | |
if ! docker inspect "$CONTAINER_ID" &>/dev/null; then | |
echo "Error: Docker container with ID '$CONTAINER_ID' doesn't exist." | |
echo "List of available Docker containers:" | |
docker ps -a --format '{{ .Names }}' | |
exit 1 | |
fi | |
IMAGE=$(docker inspect --format '{{.Config.Image}}' "$CONTAINER_ID") | |
ENV_VARS=$(docker inspect -f '{{range $index, $value := .Config.Env}} -e "{{print $value}}"{{end}}' "$CONTAINER_ID") | |
VOLUMES=$(docker inspect --format '{{ range .Mounts }} -v {{ .Source }}:{{ .Destination }}{{end}}' "$CONTAINER_ID") | |
PORTS=$(docker inspect --format '{{range $p, $conf := .NetworkSettings.Ports}} -p {{(index $conf 0).HostIp}}:{{(index $conf 0).HostPort}}:{{$p}}{{end}}' "$CONTAINER_ID") | |
USER_OPTION=$(docker inspect --format '{{.Config.User}}' "$CONTAINER_ID") | |
[[ ! -z "$USER_OPTION" ]] && USER="--user $USER_OPTION" || USER="" | |
WORKDIR_OPTION=$(docker inspect --format '{{.Config.WorkingDir}}' "$CONTAINER_ID") | |
[[ ! -z "$WORKDIR_OPTION" ]] && WORKDIR="--workdir $WORKDIR_OPTION" || WORKDIR="" | |
RESTART_POLICY=$(docker inspect --format '{{.HostConfig.RestartPolicy.Name}}' "$CONTAINER_ID") | |
[[ "$RESTART_POLICY" != "no" ]] && RESTART="--restart=$RESTART_POLICY" || RESTART="" | |
# Check if network is default, if it is hide it. | |
NETWORK=$(docker inspect --format '{{range $net_name, $net := .NetworkSettings.Networks}} --net={{$net_name}}{{end}}' $CONTAINER_ID) | |
if [ "$NETWORK_NAME" != "$CONTAINER_ID" ]; then | |
NETWORK="--net=${NETWORK_NAME}" | |
else | |
NETWORK="" | |
fi | |
echo "docker run $ENV_VARS $USER $WORKDIR $RESTART $VOLUMES $PORTS $NETWORK $IMAGE" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment