Last active
March 12, 2025 21:46
-
-
Save skwid138/b360dbab95bee28a424f350301454092 to your computer and use it in GitHub Desktop.
Dynamically parse a Dockerfile to find the image used and run commands in that image. Useful for installing packages in the exact environment the app will run in.
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 | |
### Keep the Gist updated! | |
# https://gist.github.com/skwid138/b360dbab95bee28a424f350301454092 | |
### | |
# File paths | |
DOCKERFILE="Dockerfile" | |
# Extract the image used in the builder stage (case-insensitive) | |
IMAGE=$(grep -i "^FROM .* as \+builder" "$DOCKERFILE" | head -n 1 | awk '{ print $2 }') | |
# If not found with lowercase 'as', try with uppercase 'AS' | |
if [ -z "$IMAGE" ]; then | |
IMAGE=$(grep -i "^FROM .* AS \+builder" "$DOCKERFILE" | head -n 1 | awk '{ print $2 }') | |
fi | |
# If still not found, try the first FROM statement | |
if [ -z "$IMAGE" ]; then | |
echo "Warning: Builder stage not found, using the first FROM statement..." | |
IMAGE=$(grep "^FROM " "$DOCKERFILE" | head -n 1 | awk '{ print $2 }') | |
fi | |
# Verify the image was found | |
if [ -z "$IMAGE" ]; then | |
echo "Error: Could not determine the base image from the Dockerfile." | |
exit 1 | |
fi | |
echo "Using image: $IMAGE" | |
# Check if npm command is provided | |
if [ "$#" -lt 1 ]; then | |
echo "Usage: $0 <npm-command>" | |
echo "Example: $0 npm install package" | |
exit 1 | |
fi | |
# Build the npm command from arguments | |
NPM_COMMAND="$@" | |
# Include the .env file if it exists | |
if [ -f ".env" ]; then | |
DOCKER_RUN_ARGS="--env-file .env" | |
else | |
DOCKER_RUN_ARGS="" | |
fi | |
# Run the docker command with the specified npm command | |
docker run --rm \ | |
-v "$(pwd)/.:/usr/src/app/." \ | |
-w /usr/src/app \ | |
"$IMAGE" \ | |
$NPM_COMMAND | |
# Exit with the status of the last command | |
exit $? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment