You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
1.5 KiB

#!/bin/bash
#
# This script will build the docker image and push it to a specified Docker registry.
#
# Usage: buildAndPush.sh imageName [registry]
#
# Docker image names should look like "username/appname" and must be all lower case.
# If pushing to a local registry, specify it as "localhost:5000/username/appname".
# If no registry is provided, it defaults to Docker Hub.
IMAGE_NAME=$1
REGISTRY=${2:-"docker.io"} # 默认使用 docker.io (Docker Hub),如果指定 registry 则使用指定的
if [ -z "$IMAGE_NAME" ]; then
echo "Error: Image name not provided"
echo "Usage: buildAndPush.sh imageName [registry]"
exit 1
fi
echo "Using $IMAGE_NAME as the image name"
echo "Using $REGISTRY as the registry"
# Build the Docker image
BUILD_LOG=$(mktemp)
docker build --progress=plain -t $IMAGE_NAME . > $BUILD_LOG 2>&1
BUILD_EXIT_CODE=$?
if [ $BUILD_EXIT_CODE -ne 0 ]; then
echo "Docker build failed with exit code $BUILD_EXIT_CODE"
echo "Build log:"
cat $BUILD_LOG
rm $BUILD_LOG
exit 1
fi
rm $BUILD_LOG
# Tag the image for the local registry
if [ "$REGISTRY" != "docker.io" ]; then
FULL_IMAGE_NAME="$REGISTRY/$IMAGE_NAME"
docker tag $IMAGE_NAME $FULL_IMAGE_NAME
if [ $? -ne 0 ]; then
echo "Docker tagging failed"
exit 1
fi
IMAGE_NAME="$FULL_IMAGE_NAME"
fi
# Push the Docker image
docker push $IMAGE_NAME
if [ $? -ne 0 ]; then
echo "Docker push failed"
exit 1
fi
echo "Docker image successfully pushed to $IMAGE_NAME"