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.
 

138 lines
2.9 KiB

#!/bin/bash
# Docker构建脚本
set -e
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# 打印带颜色的消息
print_message() {
echo -e "${GREEN}[INFO]${NC} $1"
}
print_warning() {
echo -e "${YELLOW}[WARNING]${NC} $1"
}
print_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
# 检查Docker是否运行
check_docker() {
if ! docker info > /dev/null 2>&1; then
print_error "Docker未运行,请启动Docker服务"
exit 1
fi
}
# 清理旧的镜像和容器
cleanup() {
print_message "清理旧的Docker资源..."
docker system prune -f
}
# 构建镜像
build_image() {
local tag=${1:-"koa3-demo:latest"}
print_message "构建Docker镜像: $tag"
docker build \
--target production \
--tag "$tag" \
--build-arg BUILDKIT_INLINE_CACHE=1 \
.
if [ $? -eq 0 ]; then
print_message "镜像构建成功: $tag"
else
print_error "镜像构建失败"
exit 1
fi
}
# 运行容器
run_container() {
local tag=${1:-"koa3-demo:latest"}
print_message "启动容器..."
docker run -d \
--name koa3-demo \
--publish 3000:3000 \
--volume "$(pwd)/database:/app/database" \
--volume "$(pwd)/logs:/app/logs" \
--env NODE_ENV=production \
--env BUN_ENV=production \
--env PORT=3000 \
"$tag"
if [ $? -eq 0 ]; then
print_message "容器启动成功"
print_message "应用运行在: http://localhost:3000"
else
print_error "容器启动失败"
exit 1
fi
}
# 使用docker-compose
use_compose() {
print_message "使用docker-compose启动服务..."
docker-compose up -d --build
if [ $? -eq 0 ]; then
print_message "服务启动成功"
print_message "应用运行在: http://localhost:3000"
else
print_error "服务启动失败"
exit 1
fi
}
# 显示帮助信息
show_help() {
echo "用法: $0 [选项]"
echo ""
echo "选项:"
echo " build [tag] 构建Docker镜像"
echo " run [tag] 运行容器"
echo " compose 使用docker-compose启动服务"
echo " cleanup 清理Docker资源"
echo " help 显示此帮助信息"
echo ""
echo "示例:"
echo " $0 build 构建镜像"
echo " $0 build v1.0 构建带标签的镜像"
echo " $0 run 运行容器"
echo " $0 compose 使用docker-compose启动"
}
# 主函数
main() {
check_docker
case "${1:-help}" in
"build")
build_image "$2"
;;
"run")
run_container "$2"
;;
"compose")
use_compose
;;
"cleanup")
cleanup
;;
"help"|*)
show_help
;;
esac
}
# 执行主函数
main "$@"