Skip to content

Instantly share code, notes, and snippets.

@fjpedrosa
Last active July 31, 2024 16:37
Show Gist options
  • Select an option

  • Save fjpedrosa/6399c8974dbe4723ba37ae04bdf34b2f to your computer and use it in GitHub Desktop.

Select an option

Save fjpedrosa/6399c8974dbe4723ba37ae04bdf34b2f to your computer and use it in GitHub Desktop.
Deploy Docker image to DigitalOcean and run services
export IMAGE_NAME="your_image_name"
export USER="your_user"
export ADDRESS="your_address"
export KEY_FILE="your_key_file"
#!/bin/bash
# Stop the script in case of errors
set -e
# Name of your Docker image
IMAGE_NAME="${IMAGE_NAME}"
# Information about your EC2 instance
USER="${USER:-root}"
ADDRESS="${ADDRESS}"
KEY_FILE="${KEY_FILE}"
# Validation: Check that all required variables have values
if [[ -z "$IMAGE_NAME" || -z "$ADDRESS" || -z "$KEY_FILE" ]]; then
echo "Error: One or more required variables are not set."
echo "IMAGE_NAME: $IMAGE_NAME"
echo "ADDRESS: $ADDRESS"
echo "KEY_FILE: $KEY_FILE"
exit 1
fi
# Name of the tar file for the Docker image
TAR_FILE="${IMAGE_NAME}.tar"
# Step 0: Build the Docker image from the Dockerfile
echo "Building docker image $IMAGE_NAME:$TAG..."
DOCKER_DEFAULT_PLATFORM=linux/amd64 docker build -t $IMAGE_NAME .
# docker build -t $IMAGE_NAME .
echo "Build completed."
# Step 1: Save the Docker image to a tar file
echo "Saving docker image $IMAGE_NAME in $TAR_FILE..."
docker save -o $TAR_FILE $IMAGE_NAME
echo "Image saved."
# Step 2: Transfer the tar file to your DigitalOcean instance
echo "Transferring $TAR_FILE to $USER@$ADDRESS..."
scp -i $KEY_FILE $TAR_FILE $USER@$ADDRESS:~/
echo "Transfer completed."
# Step 3: Load the Docker image on your DigitalOcean instance
echo "Loading image in DigitalOcean..."
ssh -i $KEY_FILE $USER@$ADDRESS "docker load -i ~/$TAR_FILE"
echo "Image loaded in DigitalOcean."
# New Step: Stop the citrux-scrapper service and restart with the new image
echo "Restarting citrux-scrapper service with the new image..."
ssh -i $KEY_FILE $USER@$ADDRESS "docker-compose stop scrapper && docker-compose rm -f scrapper && docker-compose up -d scrapper"
echo "Service citrux-scrapper restarted with the new image."
# Step 4: Delete dangling Docker images in DigitalOcean
echo "Deleting dangling docker images in DigitalOcean..."
ssh -i $KEY_FILE $USER@$ADDRESS "docker rmi \$(docker images -f 'dangling=true' -q)"
echo "Dangling images deleted."
# Step 5: Delete the Docker image
echo "Deleting docker build from local folder..."
rm -rf $IMAGE_NAME
echo "Image deleted."
# Cleanup: Optionally, you can delete the tar file from your local system and/or DigitalOcean after loading
echo "Deleting local tar file..."
rm $TAR_FILE
# echo "Deleting tar file in DigitalOcean..."
# ssh -i $KEY_FILE $USER@$ADDRESS "rm ~/$TAR_FILE"
echo "Deploy completed."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment