Skip to content

Instantly share code, notes, and snippets.

@princefishthrower
Last active December 4, 2023 19:13
Show Gist options
  • Save princefishthrower/81bc574c747b2a9f37bd2ed70d847d87 to your computer and use it in GitHub Desktop.
Save princefishthrower/81bc574c747b2a9f37bd2ed70d847d87 to your computer and use it in GitHub Desktop.
Export the source code from any Docker tag!
#!/bin/bash
#
# Extracts the source code of any Docker tag!
# Inspired by Sambhav Jain's post on DEV: https://dev.to/sambhav2612/reverse-engineering-a-docker-image-i8c
# Simply pass:
# 1. The desired Docker image tag you want to get the source code for
# 2. The target folder to put the source code in
#
# Example usage:
# ./export-source-from-docker-tag.sh gcr.io/google-samples/gb-frontend:v4 docker-source
#
#Produces output:
# WorkingDir of image is var/www/html
# Creating temporary container...
# Exporting temporary container...
# Extracting contents of WorkingDir to "docker-source"...
# Done. Source code from Docker tag "gcr.io/google-samples/gb-frontend:v4" successfully exported into folder "docker-source".
# Grep out the "WorkingDir", only first match, then remove everything uneeded, including leading slash (for tar later), and trim out leading or trailing spaces
# workingDir=$(docker image inspect gcr.io/google-samples/gb-frontend:v4 | grep -m 1 WorkingDir | sed 's/"WorkingDir"://g; s/"//g; s/,//g; s/\///; s/^[[:space:]]*//')
workingDir=$(docker image inspect $1 | grep -m 1 WorkingDir | sed 's/"WorkingDir"://g; s/"//g; s/,//g; s/\///; s/^[[:space:]]*//')
echo WorkingDir of image is $workingDir
# Count the number of nested folders this folder may be in, this is used for cleaner export further down
componentCount=$(echo $workingDir | tr -cd '/' | wc -c)
componentCount=$((componentCount+1))
# create a temporary container, redirect hash output to /dev/null
echo Creating temporary container...
docker create --name="tmp" $1 1>/dev/null
# export the container as a tar
echo Exporting temporary container...
docker export "tmp" > tmp.tar
# remove temp container
docker rm "tmp" 1>/dev/null
# make a folder named by the second argument to move files into
echo Extracting contents of WorkingDir to \"$2\"...
sourceCodeFolderName=$2
mkdir -p $sourceCodeFolderName
# extract the working dir into a folder called 'tmp'
tar -xf tmp.tar --strip-components=$componentCount -C $sourceCodeFolderName $workingDir
# clean up the no longer needed tar
rm tmp.tar
echo Done. Source code from Docker tag \"$1\" successfully exported into folder \"$2\".
@Ami-OS
Copy link

Ami-OS commented Nov 7, 2022

I have a situation where the first WorkingDir item is empty. So I trim empty lines and only use the first item (Line: 21):

workingDir=$(docker image inspect $1 | grep WorkingDir | sed 's/"WorkingDir"://g; s/"//g; s/,//g; s/\///; s/^[[:space:]]*//' | sed '/^[[:space:]]*$/d' | head -n 1)

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