Created
December 5, 2024 18:25
-
-
Save skwid138/5601d247788124fae49ffe599029ed23 to your computer and use it in GitHub Desktop.
Dynamically get a running container name, execute a command in the container, and restart the container.
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 | |
# Find the correct docker-compose file | |
if [ -f "docker-compose.yml" ]; then | |
DOCKER_COMPOSE_FILE="docker-compose.yml" | |
elif [ -f "docker-compose.yaml" ]; then | |
DOCKER_COMPOSE_FILE="docker-compose.yaml" | |
else | |
echo "Error: Could not find 'docker-compose.yml' or 'docker-compose.yaml'." | |
exit 1 | |
fi | |
echo "Using docker-compose file: $DOCKER_COMPOSE_FILE" | |
# Define the service name | |
SERVICE_NAME="app" | |
# Get the container name dynamically | |
CONTAINER_NAME=$(docker-compose -f "$DOCKER_COMPOSE_FILE" ps -q "$SERVICE_NAME") | |
# Check if the container name was found | |
if [ -z "$CONTAINER_NAME" ]; then | |
echo "Error: Could not find a running container for the service '$SERVICE_NAME'." | |
exit 1 | |
fi | |
echo "Using container: $CONTAINER_NAME" | |
# Check if a command is provided | |
if [ "$#" -lt 1 ]; then | |
echo "Usage: $0 <command>" | |
echo "Example: $0 npm install express" | |
exit 1 | |
fi | |
# Build the command from arguments | |
COMMAND="$@" | |
# Execute the command in the container | |
echo "Executing command inside container: $COMMAND" | |
docker exec "$CONTAINER_NAME" sh -c "$COMMAND" | |
# Restart the container | |
echo "Restarting the container" | |
docker-compose -f "$DOCKER_COMPOSE_FILE" restart "$SERVICE_NAME" | |
echo "Operation completed." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment