容器部署springboot项目--入门

1. 环境准备

确认安装docker desktop,参考docker desktop安装

2. 项目准备

2.1 springboot项目

完成springboot项目,确保可以打包为可执行jar
pom.xml 关键配置

 <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

项目打包

# Maven 项目
mvn clean package -DskipTests

# Gradle 项目
./gradlew clean build -x test

2.2 创建 Dockerfile文件

# 使用基础的 Java 镜像
FROM eclipse-temurin:21-jdk-alpine

# 设置工作目录
WORKDIR /app
# 将打包好的 JAR 文件复制到容器中
COPY target/*.jar /app/app.jar

# 暴露 Spring Boot 应用的端口
EXPOSE 8080

# 运行 Spring Boot 应用
CMD ["java", "-jar", "app.jar"]

2.3 构建 Docker 镜像

docker build -t my-spring-app:1.0.0 .

2.4 运行docker镜像

docker run -d \
  --name spring-app \
  -p 8080:8080 \
  my-spring-app:1.0.0

3. 调试

3.1 进入容器调试:

docker exec -it spring-app sh

3.2 查看应用日志:

docker logs --tail 100 -f spring-app

3.3 端口检查:

# 容器内部
docker exec spring-app nc -zv localhost 8080

# 宿主机
curl http://localhost:8080/actuator/health

4. 常见问题解决

4.1 Spring Boot 应用在打包/启动阶段无法连接 Docker 容器中的 Redis

  1. 打包时不连接 Redis,运行时通过环境变量注入真实地址。其他类似容器服务也可以
# application.yml
spring:
  redis:
    host: ${REDIS_HOST:localhost}  # 默认localhost,可由环境变量覆盖
    port: ${REDIS_PORT:6379}
  1. 启动容器时确保java项目和redis服务在同一个网络,可以参考docker 容器通信
docker run -d \
  --name spring-app \
  -p 8080:8080 \
  -e REDIS_HOST=redis-server \  # Docker 容器名
  -e REDIS_PORT=6379 \
  --net subnetwork \
  --ip 192.168.0.5  \
  my-spring-app:1.0.0

4.2 项目打包后未包含直接引用的本地 JAR 文件

项目结构:

project-root/
├── libs/           # 存放自定义JAR
│   └── custom-lib-1.0.0.jar
├── src/
└── pom.xml

更新 pom.xml 文件配置,在build->plugins-plugin节点增加 configuration 节点

<dependencies>
    <!-- 自定义依赖 -->
    <dependency>
        <groupId>com.example</groupId>
        <artifactId>custom-lib</artifactId>
        <version>1.0.0</version>
        <scope>system</scope>
        <systemPath>${project.basedir}/libs/custom-lib-1.0.0.jar</systemPath>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <!-- 关键:包含系统作用域依赖 -->
                <includeSystemScope>true</includeSystemScope>
            </configuration>
        </plugin>
    </plugins>
</build>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值