Skip to content

Instantly share code, notes, and snippets.

@zigang93
Created August 8, 2024 07:54
Show Gist options
  • Save zigang93/ed3d6b3a0be76cb8939c3202219421a6 to your computer and use it in GitHub Desktop.
Save zigang93/ed3d6b3a0be76cb8939c3202219421a6 to your computer and use it in GitHub Desktop.
Run docker image at background and remove image before deploy
#!/bin/bash
if [ -z "$1" ]; then
echo "Please provide the image registry as the first argument."
exit 1
fi
if [ -z "$2" ]; then
echo "Please provide the image name as the second argument."
exit 1
fi
if [ -z "$3" ]; then
echo "Please provide the image tag env as the third argument."
exit 1
fi
if [ -z "$4" ]; then
echo "Please provide the docker external port as the 4th argument."
exit 1
fi
if [ -z "$5" ]; then
echo "Please provide the docker internal port as the 5th argument."
exit 1
fi
# Store the argument in a variable
IMAGE_REGISTRY="$1"
IMAGE_NAME="$2"
IMAGE_TAG="$3"
DOCKER_PORT="$4"
DOCKER_INTERNAL_PORT="$5"
echo "Pull Image ${IMAGE_NAME}:${IMAGE_TAG} from ${IMAGE_REGISTRY}"
docker pull "${IMAGE_REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG}"
echo "Remove existing container"
docker stop "${IMAGE_NAME}" && docker rm $(docker ps -a -f status=exited -f status=dead -q) && docker rmi $(docker images --filter "dangling=true" -q --no-trunc)
echo "Do Deployment at port ${DOCKER_PORT}"
docker run --name "${IMAGE_NAME}" -d --restart unless-stopped -p "${DOCKER_PORT}":"${DOCKER_INTERNAL_PORT}" "${IMAGE_REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment