You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring应用本地构建后入Docker可运行,Docker内构建则无法运行

在Docker中构建并运行Spring Boot应用的问题

问题背景

原本我先在本地执行mvn clean package生成JAR包,再将其复制到Docker镜像中运行,这个流程能正常工作。但现在我想改用Docker多阶段构建,直接在容器内部完成JAR包的构建,结果镜像运行失败。

项目核心配置

Security配置类

package com.qcphotos.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(requests -> {
                requests.requestMatchers(
                        HttpMethod.GET,
                        "/products",
                        "products/parseUrl",
                        "/products/popular",
                        "/products/viewCount"
                )
                .permitAll()
                .requestMatchers(
                        HttpMethod.GET,
                        "/affiliates/redirect",
                        "/affiliates/url"
                )
                .permitAll()
                .requestMatchers(
                        HttpMethod.GET,
                        "/collections/{collectionId}",
                        "/collections/{collectionId}/products"
                )
                .permitAll()
                .requestMatchers(
                        HttpMethod.GET,
                        "/users/{userId}"
                )
                .permitAll()
                .requestMatchers(
                        HttpMethod.GET,
                        "/storefronts",
                        "/shippingAgents"
                )
                .permitAll()
                .requestMatchers("/login/oauth2/code/discord", "/")
                .permitAll()
                .anyRequest()
                .authenticated();
        })
        .csrf(csrf -> csrf.disable())
        .oauth2Login(Customizer.withDefaults());

        return http.build();
    }
}

application.yml配置

spring:
  security:
    oauth2:
      client:
        registration:
          discord:
            client-id: 'myClientId'
            client-secret: 'mySecretCode'
            authorization-grant-type: authorization_code
            scope:
              - identify
              - email
            redirect-uri: '{baseUrl}/login/oauth2/code/discord'
            client-name: Discord
        provider:
          discord:
            authorization-uri: https://discordapp.com/api/oauth2/authorize
            token-uri: https://discordapp.com/api/oauth2/token
            user-info-uri: https://discordapp.com/api/users/@me
            user-name-attribute: username

启动类

package com.qcphotos;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration;

@SpringBootApplication(exclude = {
        RepositoryRestMvcAutoConfiguration.class
})

public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

本地构建流程(可正常运行)

Dockerfile

FROM openjdk:21
WORKDIR /app
COPY /target/rest-api-1.0-SNAPSHOT-jar-with-dependencies.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]

执行步骤:

  1. 本地执行mvn clean package生成JAR包到target目录
  2. 构建Docker镜像并运行,应用正常启动

Docker多阶段构建流程(运行失败)

Dockerfile

# Build
FROM maven:3.9.7-eclipse-temurin-21 AS build
COPY ./backend /src
WORKDIR /src
RUN mvn clean package

# Run
FROM openjdk:21
WORKDIR /app
COPY --from=build /src/rest-api/target/rest-api-1.0-SNAPSHOT-jar-with-dependencies.jar app.jar
EXPOSE 8080
CMD ["java", "-jar", "app.jar"]

报错信息

Error: Could not find or load main class com.qcphotos.Application
Caused by: java.lang.ClassNotFoundException: com.qcphotos.Application

问题诊断与解决方案

  1. 修正JAR包路径
    检查项目结构:如果是单模块项目,Maven构建后的JAR包会生成在/src/target/目录下,而非/src/rest-api/target/。修改Dockerfile中的复制路径:

    COPY --from=build /src/target/rest-api-1.0-SNAPSHOT-jar-with-dependencies.jar app.jar
    
  2. 确认Maven构建配置
    确保pom.xml中配置了正确的打包插件,比如Spring Boot插件,保证生成的是可执行JAR:

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>3.2.0</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    
  3. 验证构建上下文
    执行docker build时,确保当前工作目录是项目根目录,./backend确实指向包含pom.xml的文件夹。

  4. 检查构建产物
    可以在构建阶段添加命令验证JAR包是否生成:

    RUN mvn clean package && ls -la /src/target/
    

内容的提问来源于stack exchange,提问作者Eli Chandler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 00:45:55