Spring Boot 내부에 Angular 애플리케이션 배포

시나리오를 상상해보십시오. Angular로 작성되고 백엔드로 Spring Boot Rest API로 구동되는 프론트엔드 애플리케이션을 개발했습니다. 대부분의 경우 배포할 때 각 애플리케이션을 자체 컨테이너(Firebase의 프론트엔드, Heroku의 백엔드 등)로 배포합니다. 하지만 두 앱을 단일 JAR 또는 WAR 파일로 배포할 수 있다는 것을 알고 계셨습니까?

언제 그리고 왜?



하나의 파일에 Angular/Spring Boot(또는 일반적으로 모든 Java 프로젝트)를 배포하는 것은 백엔드와 프론트엔드가 함께 개발되거나 가까운 미래에 개발될 때 또는 귀하, 귀하의 팀 또는 회사가 마이크로 서비스 접근 방식의 열렬한 팬이 아닙니다(또는 단지 모놀리식 프로젝트를 생성하기를 원함).

이러한 종류의 모놀리스 접근 방식은 앱의 (수동) 배포를 단순화하지만 한 가지 큰 단점이 있습니다. 백엔드 또는 프론트엔드를 업데이트할 때마다 새 JAR/WAR 파일을 생성해야 하므로 이 접근 방식은 CI에 가장 적합하지 않을 수 있습니다./CD 기반 프로젝트.

어떻게?



Disclaimer: some parts of this tutorial may not be best practices used in production or best practice for building apps used by thousands or millions of users. But it is how our team handles application deployment for production applications used every day by hundreds of users.



0. Angular 라우팅을 위한 useHash 전략



This is simplest way of "fixing" refreshing and direct access to Angular app via URL. You could also rewrite all routes to index.html file (by changing your server's configuration).



라우팅 파일( app-routing.module.ts )을 찾아 다음 코드 줄을 추가/바꿉니다.

@NgModule({
imports: [RouterModule.forRoot(routes, { useHash: true })],
exports: [RouterModule],
})
export class AppRoutingModule {}


이제부터 모든 Angular URL에는 도메인(포트 유무에 관계없이)과 하위 경로 사이에 /#/가 있습니다.
예: localhost:4200/login/ 는 이제 localhost:4200/#/login/ 입니다.

1. Angular 프론트엔드 구축



먼저 Angular 프로젝트에서 index.html 파일을 확인하십시오. 이 줄을 찾으십시오(찾을 수 없으면 and 사이에 추가).


<base href="/">



둘째, AngularCLI를 사용하여 각도 프로젝트를 빌드합니다.


ng build --prod



If your app is going to be run on subpath (for example domain.com/my-app/) then add --base-href=/my-app/ to build command.



2. Angular dist 폴더를 백엔드로 복사



Angular check/dist 폴더를 성공적으로 빌드한 후 내부에 앱과 같은 이름의 하위 폴더가 있어야 하며 그 안에 html, js 및 css 파일이 있습니다.

해당 파일을 백엔드에 복사합니다/src/main/resources/public/(일부 폴더가 누락된 경우 추가).

3. 백엔드 프로젝트 빌드 및 실행



다음을 사용하여 백엔드를 클린 빌드하십시오.

mvn clean package


빌드 후 다음을 사용하여 실행하십시오.

java -jar ./target/.jar


그러나 프로젝트 구성이 건물WAR로 설정된 경우에는 작동하지 않습니다. 이 경우 Java 응용 프로그램 서버(예: Tomcat, Wildfly 또는 Glasfish)에 응용 프로그램을 배포해야 합니다. 이것은 이 기사의 범위를 벗어납니다.

Spring Boot 앱을 실행한 후 WelcomePageHandlerMapping 의 로그가 표시되어야 합니다.

INFO 10732 --- [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page: class path resource [public/index.html]


우리는 끝났습니다 :)

4. 프론트엔드 접근

When your project is up and runnning you can access your frontend on domain.com/#/.

좋은 웹페이지 즐겨찾기