Spring Boot 集成 Docker 构建与发版完整指南

发布于:2025-08-30 ⋅ 阅读:(18) ⋅ 点赞:(0)

一、环境准备

1. 安装 Docker

  • Windows/macOS:下载 Docker Desktop
  • Linux(以Ubuntu为例):
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io
sudo systemctl enable docker
sudo systemctl start docker

2. 验证安装

docker --version
docker-compose --version
docker run hello-world

二、Spring Boot 项目配置

1. 添加 Maven 插件

在 pom.xml 中添加 Docker 构建插件:

<build>
    <plugins>
        <plugin>
            <groupId>com.spotify</groupId>
            <artifactId>dockerfile-maven-plugin</artifactId>
            <version>1.4.13</version>
            <executions>
                <execution>
                    <id>default</id>
                    <goals>
                        <goal>build</goal>
                        <goal>push</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <repository>${docker.image.prefix}/${project.artifactId}</repository>
                <tag>${project.version}</tag>
                <buildArgs>
                    <JAR_FILE>target/${project.build.finalName}.jar</JAR_FILE>
                </buildArgs>
            </configuration>
        </plugin>
    </plugins>
</build>

2. 创建 Dockerfile

在项目根目录创建 Dockerfile:

# 使用 OpenJDK 官方镜像作为基础镜像
FROM openjdk:17-jdk-slim

# 设置工作目录
WORKDIR /app

# 复制构建好的 jar 包到容器中
ARG JAR_FILE
COPY ${JAR_FILE} app.jar

# 暴露端口
EXPOSE 8080

# 启动应用
ENTRYPOINT ["java", "-jar", "app.jar"]

3. 多阶段构建优化(可选)

对于生产环境,推荐使用多阶段构建减小镜像体积:

# 构建阶段
FROM maven:3.8.4-openjdk-17 AS build
WORKDIR /app
COPY pom.xml .
COPY src ./src
RUN mvn clean package -DskipTests

# 运行阶段
FROM openjdk:17-jdk-slim
WORKDIR /app
COPY --from=build /app/target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]

三、构建与运行

1. 构建 Docker 镜像

# 先打包项目
mvn clean package

# 构建 Docker 镜像
mvn dockerfile:build

# 或者直接使用 docker 命令
docker build -t my-spring-app:1.0.0 .

2. 运行容器

# 运行容器
docker run -d -p 8080:8080 --name my-app my-spring-app:1.0.0

# 查看运行日志
docker logs -f my-app

3. 验证应用

访问 http://localhost:8080 查看应用是否正常运行

四、高级配置

1. 使用 Docker Compose

创建 docker-compose.yml 文件:

version: '3.8'

services:
  app:
    image: my-spring-app:1.0.0
    container_name: spring-app
    ports:
      - "8080:8080"
    environment:
      - SPRING_PROFILES_ACTIVE=prod
    volumes:
      - ./logs:/app/logs
    networks:
      - app-network

  redis:
    image: redis:alpine
    ports:
      - "6379:6379"
    networks:
      - app-network

networks:
  app-network:
    driver: bridge

启动服务:

docker-compose up -d

2. 集成 CI/CD(GitHub Actions 示例)

创建 .github/workflows/docker-publish.yml:

name: Docker Build and Push

on:
  push:
    branches: [ main ]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      
      - name: Set up JDK 17
        uses: actions/setup-java@v2
        with:
          java-version: '17'
          distribution: 'temurin'
          
      - name: Build with Maven
        run: mvn clean package
        
      - name: Login to Docker Hub
        uses: docker/login-action@v1
        with:
          username: ${{ secrets.DOCKER_HUB_USERNAME }}
          password: ${{ secrets.DOCKER_HUB_TOKEN }}
          
      - name: Build and push
        uses: docker/build-push-action@v2
        with:
          context: .
          push: true
          tags: your-dockerhub-username/my-spring-app:latest

五、生产环境最佳实践

1. 镜像优化

  • 使用 .dockerignore 文件排除不必要的文件:
.git
.mvn
target
*.iml

2. 安全加固

  • 使用非 root 用户运行:
RUN addgroup -S spring && adduser -S spring -G spring
USER spring

3. 健康检查

HEALTHCHECK --interval=30s --timeout=3s \
  CMD curl -f http://localhost:8080/actuator/health || exit 1

4. 日志管理

# 查看日志
docker logs my-app

# 持久化日志
docker run -v /path/on/host:/app/logs my-spring-app

六、常见问题解决

1. 时区问题

ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

2. 内存限制

docker run -d -m 512m --memory-swap 1G my-spring-app

3. 多环境配置

docker run -e "SPRING_PROFILES_ACTIVE=prod" my-spring-app

七、Kubernetes 部署(可选)

1. 创建 deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: spring-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: spring-app
  template:
    metadata:
      labels:
        app: spring-app
    spec:
      containers:
      - name: spring-app
        image: my-spring-app:1.0.0
        ports:
        - containerPort: 8080
        resources:
          limits:
            memory: "512Mi"
            cpu: "500m"

2. 创建 service.yaml

apiVersion: v1
kind: Service
metadata:
  name: spring-app-service
spec:
  selector:
    app: spring-app
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
  type: LoadBalancer

3. 部署到 Kubernetes

kubectl apply -f deployment.yaml
kubectl apply -f service.yaml

通过以上步骤,您已经完成了 Spring Boot 项目与 Docker 的完整集成,实现了从开发到生产的全流程容器化部署。


网站公告

今日签到

点亮在社区的每一天
去签到