Created
March 18, 2024 21:18
-
-
Save madan712/76829bd78ccd04651fc912ac84a1ac34 to your computer and use it in GitHub Desktop.
Shell script to manage docker process using pm2
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
#!/usr/bin/env bash | |
set -euo pipefail | |
# Variables | |
IMAGE_NAME="my_image_name" | |
CONTAINER_NAME="my_container_name" | |
TAG="latest" | |
# Build Docker image | |
docker build -t "${IMAGE_NAME}" . | |
# Check if the container is already running | |
if [[ $(pm2 pid "$CONTAINER_NAME") ]]; then | |
# Container exists, update and restart | |
echo "Container ${CONTAINER_NAME} already exists. Updating and restarting..." | |
# Stop the existing container | |
pm2 stop ${CONTAINER_NAME} | |
# Remove the existing container | |
docker rm -f ${CONTAINER_NAME} | |
# Remove the process | |
pm2 delete ${CONTAINER_NAME} | |
# Save process after delete | |
pm2 save | |
else | |
# Container doesn't exist, start a new one | |
echo "Container ${CONTAINER_NAME} doesn't exist. Starting a new one..." | |
fi | |
# Run the Docker container | |
pm2 start docker --name ${CONTAINER_NAME} -- run --name ${CONTAINER_NAME} -p 3000:3000 -e ENV="${ENV}" --env-file "/root/backend.env_${ENV}" --restart=always ${IMAGE_NAME}:${TAG} | |
# Save process in pm2 | |
pm2 save | |
# Remove dangling images | |
docker system prune -f |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment