如何在Apache Tomcat服务器中运行Angular 4.6应用程序?
Hey there! Since you're new to Angular 4.6, let's walk through the deployment process step by step—no confusing hoops to jump through, just straightforward actions to get your app live on Tomcat.
Step 1: Build Your Angular App for Production
First, you need to compile your project into static files that Tomcat can serve. Open your terminal, navigate to your Angular project's root folder, and run this command:
ng build --prod
This will generate a dist folder in your project directory. Inside it, you’ll find all the compiled HTML, CSS, JS, and asset files—this is the package we’ll deploy to Tomcat.
Step 2: Move Files to Tomcat’s Web Directory
- Find your Apache Tomcat installation folder, then head to the
webappssubfolder. - Create a new folder inside
webapps(e.g.,my-angular-app—this will become the URL path for your app). - Copy every file and subfolder from the
distdirectory into this new folder you just made.
Step 3: Fix the SPA Routing 404 Issue
Angular uses client-side routing, which means if you refresh a specific route (like http://localhost:8080/my-angular-app/profile), Tomcat will throw a 404 error because it doesn’t recognize that server-side path. Here’s how to fix it:
- Inside your app’s folder in
webapps(e.g.,webapps/my-angular-app), create aWEB-INFfolder if it doesn’t exist. - Create a
web.xmlfile insideWEB-INFwith this content:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <error-page> <error-code>404</error-code> <location>/index.html</location> </error-page> </web-app>
This tells Tomcat to redirect any 404 errors back to Angular’s index.html, which will handle the client-side routing correctly.
Step 4: Start Tomcat and Test Your App
- Launch your Tomcat server (run
startup.baton Windows orstartup.shon Linux/macOS from thebinfolder of your Tomcat installation). - Open your browser and go to
http://localhost:8080/my-angular-app(replacemy-angular-appwith the folder name you chose earlier). - Test navigating through your app’s routes and refreshing pages—everything should work without hitting 404 errors now!
内容的提问来源于stack exchange,提问作者Rajan Desai

