部署
Posted at
# blog
部署
docker
- 使用
apt
更新并安装依赖包
sudo apt-get update
sudo apt-get install \
ca-certificates \
curl \
gnupg \
lsb-release
- 添加 Docker 官方 GPG 密钥
sudo mkdir -p /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
设置仓库
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
$(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
- 安装 Docker Engine
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io docker-compose-plugin
- 验证是否安装成功
sudo docker run hello-world
安装 Docker Compose
下载
sudo curl -SL https://github.com/docker/compose/releases/download/v2.14.2/docker-compose-linux-x86_64 -o /usr/local/bin/docker-compose
# 上面的速度太慢可以尝试换源
# sudo curl -SL https://get.daocloud.io/docker/compose/releases/download/v2.14.2/docker-compose-linux-x86_64 -o /usr/local/bin/docker-compose
授权
sudo chmod +x /usr/local/bin/docker-compose
运行
# 拉取项目
git clone https://github.com/szluyu99/gin-vue-blog
cd gin-vue-blog
cd deploy
./bootstrap.sh
代码分析
bootstrap:引导
#!/bin/bash
if [ "$1" == "dev" ]; then
# 开发环境, 使用本机的 pnpm 环境打包 (相对于 start/Dockerfile 的路径)
export WEB_BUILD_CONTEXT="../build/web"
./build_web.sh
else
# 生产环境, 使用 docker 容器的 node 打包
export WEB_BUILD_CONTEXT="../.."
fi
# 清理旧容器
./clean_docker.sh
# 启动新容器
cd start
docker-compose up -d --build
build_web.sh
#!/bin/bash
# 未安装 pnpm 则安装
if ! command -v pnpm &> /dev/null; then
npm install -g pnpm
else
echo "pnpm 已安装"
fi
# 打包 gin-blog-front 并移到 docker 部署目录
cd ../gin-blog-front
pnpm install
pnpm build
rm -rf ../deploy/build/web/dist_blog
mv ./dist ../deploy/build/web/dist_blog
# 打包 gin-blog-admin 并移到 docker 部署目录
cd ../gin-blog-admin
pnpm install
pnpm build
rm -rf ../deploy/build/web/dist_admin
mv ./dist ../deploy/build/web/dist_admin
clean_docker.sh
#!/bin/bash
# 清理本项目构建的 Docker 容器
stop_and_remove_container() {
container_name=$1
if docker ps -a --format '{{.Names}}' | grep -q "$container_name"; then
docker stop $container_name
docker rm $container_name
echo "已经停止并删除容器 $container_name"
else
echo "未找到容器 $container_name"
fi
}
stop_and_remove_container "gvb-web"
stop_and_remove_container "gvb-server"
stop_and_remove_container "gvb-redis"
stop_and_remove_container "gvb-mysql"
echo "本项目相关 Docker 容器清理完成"
docker-compose
docker-compose
命令启动Docker容器。-d
参数表示在后台运行容器,--build
参数表示在启动容器之前先构建镜像。