Angular and Spring Boot are extremely popular, and used often while creating modern apps. When looking for popular search terms in Google’s Keyword Planner, these two together appear often. What comes out of this is a summary of monthly searches, which are unlimited by location, and averaged.

A series of tutorials on Angular and Spring Boot has led to this fourth and final tutorial. Throughout this series one is taught how to use Angular and Spring Boot + Kotlin in order to create a more secure notes app, how to add Bootstrap for CSS, as well as making it easy to interact with data tables. Second to last, the tutorials show how to deploy apps separately to  Heroku. In addition to this, the tutorial shows how to use the ng deploy to deploy AWS, Firebase, and Netlify. Tutorials are linked below. 

  1. Build a CRUD App with Angular 9 and Spring Boot 2.2
  2. Build Beautiful Angular Apps with Bootstrap
  3. Angular Deployment with a Side of Spring Boot

In this tutorial, I will be outlining the use of Docker in order to create images for Angular, and deploy said images to Heroku, how to use both Angular and Spring Boot into the same JAR artifact for deployment. I will also include how to Dockerize combined clips using Cloud Native Buildpacks and Jib, and how to deploy personal Docker images to Cloud Foundry, Knative on Google Cloud, and Heroku.

The most popular way to build and share containers is by far Docker. ‘Dockerizing’ is when you package your app, which can also involve adding web servers to your app. When containerizing an Angular app, this can become very important because an Angular app only has its artifacts as JavaScript, CSS, and HTML, which means that the product app will need to serve up its static files by a web server. If you are worried about security, the webserver has the ability to send security headers by configuring it, making it much safer for users.

Table of Contents

I’d like to thank many folks for their help with this post. Benoit Sautel for help with Gradle + Kotlin, Ray Tsang for help with Jib, James Ward for help with Knative, Josh Long for his assistance with Docker + Cloud Foundry, and Joe Kutner for his buildpacks support. Y’all rock! ��

You can also watch this tutorial as a screencast!

To begin, clone the GitHub repo from the most recent tutorial in this series.



Secure Your Angular + Spring Boot App with OpenID Connect

OAuth 2.0 was finalized in 2012 and has since become the industry-standard protocol for authorization. In 2014, OpenID Connect (OIDC) extended OAuth, adding federated identity to delegated authorization. Together, these two layers offer a standard specification that developers can write code against in a way that will work across multiple identity providers.

To begin the process of adding OIDC to Angular and Spring Boot, you’ll need to create a Heroku account. If you already have a Heroku account, log into it. Once you’re logged in, create a new app. I named mine bootiful-angular.

After creating your app, click on the Resources tab and add the Okta add-on.

If you haven’t entered a credit card for your Heroku account, you will get an error. This is because Heroku requires you to have a credit card on file to use any of their add-ons, even free ones. This is part of Heroku’s assurance to guard against misuse (real person, real credit card, etc.). I think this is a good security practice. Add a credit card to continue.

Click Provision and wait 20-30 seconds while your Okta account is created and OIDC apps are registered. Now go to your app’s Settings tab and click the Reveal Config Vars button. The variables displayed are the environment variables you can use to configure both Angular and Spring Boot for OIDC authentication.

Create an okta.env file in the angular-spring-boot-docker/notes-api directory and copy the variable values into it, where $OKTA_* is the value from Heroku.

Start your Spring Boot app by navigating to the notes-api directory, sourcing this file, and running bootRun.

For Windows users, the commands will be:

Next, configure Angular for OIDC authentication by modifying its auth-routing.module.ts to use the generated issuer and SPA client ID.


Install your Angular app’s dependencies and start it.

Open http://localhost:4200 in your browser.

Click the Login button in the top right corner. You should be logged in without seeing a login form because you’re already logged in to Okta. If you want to see the full authentication flow, log out, or try it in a private window. You can use the $OKTA_ADMIN_EMAIL and $OKTA_ADMIN_PASSWORD from your Heroku config variables for credentials. Create a note to make sure everything works.

Commit your progress to Git from the top-level angular-spring-boot-docker directory.

Create a notes/Dockerfile that uses Node and Nginx as a web server.

When I was trying to get everything to work, I found it handy to comment out the RUN ng build --prod line and use the following instead.

This allows you to skip the lengthy Angular build process.

This will build your project and add Nginx as a web server. You’ll need to create the nginx.config file to make Nginx SPA-aware.


Make sure your Docker daemon is running with docker ps. Then run the following command to build your Docker image. The ng-notes value can be whatever you want to name your image.

If it builds successfully, you’ll see messages like the following:

You can run it locally on port 4200 using the docker run command.

Add these Docker commands as scripts to your package.json file.

The docker run command will serve up the production version of the Angular app, which has its backend configured to point to a production URL on Heroku.


You’ll need to deploy your Spring Boot app to a similar public URL for your Angular + Docker container to work in production.

If you already deployed Spring Boot to Heroku (from the last tutorial), you can skip the next section and go straight to deploying your Angular Docker container to Heroku.

Deploy Spring Boot to Heroku

One of the easiest ways to interact with Heroku is with the Heroku CLI. Install it before proceeding with the instructions below.

Open a terminal and log in to your Heroku account.

You should already have a Heroku app that you’ve added Okta to. You can use it for hosting your Spring Boot app. Run heroku apps and you’ll see the one that you created.

You can run heroku config -a $APP_NAME to see your Okta variables. In my case, I’ll be using bootiful-angular for $APP_NAME.

Associate your existing Git repo with the app on Heroku.

Set the APP_BASE config variable to point to the notes-api directory. While you’re there, add the monorepo and Gradle buildpacks.

Attach a PostgreSQL database to your app.

By default, Heroku’s Gradle support runs ./gradlew build -x test. Since you want it to run ./gradlew bootJar -Pprod, you’ll need to override it by setting a GRADLE_TASK config var.

The $OKTA_* environment variables don’t have the same names as the Okta Spring Boot starter expects. This is because the Okta Heroku Add-On creates two apps: a SPA and a web app. The web app’s config variables end in _WEB. You’ll have to make some changes so those variables are used for the Okta Spring Boot starter. Run the following command and remove _WEB from the two variables that have it.

Now you’re ready to deploy! Heroku makes this easy with a simple git push.

By default, JPA is configured to create your database schema each time. Change it to simply validate the schema.

Now, you’ll need to configure your Angular app to use your Heroku-deployed Spring Boot app for its production URL.


Since this runs the production build, you’ll need to add http://localhost:4200 as an allowed origin in your Spring Boot app on Heroku. Run the following command and add it to the end of the existing values.

One advantage of doing this is that you can run your local Angular app against your production backend. I’ve found this very useful when debugging and fixing UI issues caused by production data.

Now you should be able to rebuild your Angular Docker container and run it.

Open your browser to http://localhost:4200, log in, and confirm you can add notes.

Verify the data made it to Heroku by going to https://<your-heroku-app>

Heroku has several slick features when it comes to Docker images. If your project has a Dockerfile, you can deploy your app directly using the Heroku Container Registry.

First, make sure you’re in the notes directory, then log in to the Container Registry.

Then, create a new app.

Add the Git URL as a new remote named docker.

You’ll need to update nginx.config so it reads from a $PORT environment variable if it’s set, otherwise default it to 80. You can use envsubst to do this at runtime. However, the default envsubst doesn’t allow default variables. The good news is a8m/envsubst on GitHub does!

Replace your nginx.config with the following configuration that defaults to 80 and escapes the $uri variable so it’s not replaced with a blank value.


You’ll also need to update your Dockerfile so it uses the aforementioned envsubstr.


Then, push your Docker image to Heroku’s Container Registry.

Once the push process has completed, release the image of your app:

And open the app in your browser:

You’ll need to add your app’s URL to Okta as a valid redirect URI. In your Spring Boot app on Heroku, go to Resources and click on the Ookta add-on. This will log you in to your Okta dashboard. Navigate to ApplicationsSPAGeneralEdit. Add the following redirect URIs.

You’ll need to add the new app’s URL as an allowed origin in your Spring Boot app on Heroku. Copy the printed Hosting URL value and run the following command.

Add the new URL after your existing localhost one, separating them with a comma. For example:

Now you should be able to log in and see the note you created earlier.

A-Rated Security Headers for Nginx in Docker

If you test your freshly-deployed Angular app with, you’ll get an F. To solve this, modify your nginx.config to add security headers.


After updating this file, run the following commands:

Now you should get an A!

Commit your changes to Git.

In the previous sections, you learned how to deploy your Angular and Spring Boot apps separately. Now I’ll show you how to combine them into a single JAR for production. You’ll still be able to run them independently in development, but deploying them to production will be easier because you won’t have to worry about CORS (cross-origin resource sharing). I’ll also convert the OAuth flows so they all happen server-side, which is more secure as the access token won’t be stored in the browser.

Update Your Angular App’s Authentication Mechanism

Create a new AuthService service that will communicate with your Spring Boot API for authentication logic.


  1. Talk to the /users endpoint to determine authenticated status. A username will be returned if the user is logged in.
  2. When the user clicks a login button, redirect them to a Spring Security endpoint to do the OAuth dance.
  3. Logout using the /api/logout endpoint, which returns the Okta Logout API URL and a valid ID token.

Create a user.ts file in the same directory, to hold your User model.


Update app.component.ts to use your new AuthService in favor of OktaAuthService.


Remove OktaAuthModule and its related code from app.component.spec.ts and home.component.spec.ts. You’ll also need to add HttpClientTestingModule to their TestBed imports.

Change the buttons in app.component.html to reference the auth service instead of oktaAuth.


Update home.component.ts to use AuthService too.


Delete notes/src/app/auth-routing.module.ts and notes/src/app/shared/okta.

Modify app.module.ts to remove the AuthRoutingModule import, add HomeComponent as a declaration, and import HttpClientModule.


Add the route for HomeComponent to app-routing.module.ts.


Change both environments.ts and to use a blank apiUrl.

Create a proxy.conf.js file to proxy certain requests to your Spring Boot API on http://localhost:8080.


Add this file as a proxyConfig option in angular.json.


Remove Okta’s Angular SDK and OktaDev Schematics from your Angular project.

At this point, your Angular app doesn’t contain any Okta-specific code for authentication. Instead, it relies on your Spring Boot app to provide that.

You should still be able to run ng serve in your Angular app and ./gradlew bootRun in your Spring Boot app for local development. However, you’ll need to make some adjustments to your Spring Boot app to include Angular for production.

Configure Spring Boot to Include Your Angular SPA

In your Spring Boot app, you’ll need to change a number of things. You’ll need to configure Gradle to build your Angular app when you pass in -Pprod, you’ll need to adjust its routes (so it’s SPA-aware and routes all 404s to index.html), and you’ll need to modify Spring Security to allow HTML, CSS, and JavaScript to be anonymously accessed.

To begin, delete src/main/kotlin/com/okta/developer/notes/HomeController.kt. You’ll no longer need this because your Angular app will be served up at the / path.

Next, create a RouteController.kt that routes all requests to index.html.


Modify SecurityConfiguration.kt to allow anonymous access to static web files, the /user info endpoint, and to add additional security headers.


With Kotlin, you can mark parameters and return values as optional by adding ? to their type. Update the user() method in UserController.kt to make OidcUser optional. It will be null when the user is not authenticated, that’s why this change is needed.


Previously, Angular handled logout. Add a LogoutController that will handle expiring the session as well as sending information back to Angular so it can logout from Okta.


In OpenID Connect Logout Options with Spring Boot, Brian Demers describes this as RP-Initiated Logout. He also shows how you can configure Spring Security’s OidcClientInitiatedLogoutSuccessHandler to logout. I tried this technique but decided against it because it doesn’t allow me to redirect back to my Angular app in dev mode. I also encountered some CORS errors that I was unable to solve.

When you access the /user/notes endpoint with Angular, the ${} expression correctly resolves to the user’s email. However, when you access this endpoint after logging in directly to Spring Boot, it resolves to the sub claim. To make these values consistent, add the following property to and

You can also remove the property from both files since Angular will proxy the request in development (eliminating the need for CORS) and there won’t be cross-domain requests in production.

Add a server.port property to that uses a PORT environment variable, if it’s set.

Because there won’t be any cross-domain requests, you can remove the simpleCorsFilter bean and allowedOrigins variable in DemoApplication.kt, too.

Modify Gradle to Build a JAR with Angular Included

Now that your Spring Boot app is ready to serve up your Angular app, you need to modify your Gradle configuration to build your Angular app and package it in the JAR.

Start by importing NpmTask and adding the Node Gradle plugin.


Then, define the location of your Angular app and configuration for the Node plugin.

Add a buildWeb task:

And modify the processResources task to build Angular when -Pprod is passed in.

Now you should be able to combine both apps using ./gradlew bootJar -Pprod. Once it’s built, run it with the following commands to ensure everything works.

Congrats! You modified your Angular and Spring Boot apps to be packaged together and implemented the most secure form of OAuth 2.0 to boot! ��

Commit your changes to Git.

Since everything is done via Gradle now, you can use plugins to build a Docker container. Jib builds optimized Docker images without the need for deep mastery of Docker best-practices. It reads your Gradle/Maven build files for its metadata.

To add Jib support, add its Gradle plugin.


Then, at the end of this file, add jib configuration to specify your image name and the active Spring profile.

Run the following command to build a Docker image with Jib.

If you want to override the image name in build.gradle.kts, you can pass in an --image parameter. For example, ./gradlew jibDockerBuild -Pprod --image=bootiful-ng9.

Run Your Spring Boot Docker App with Docker Compose

In theory, you should be able to run the following command to run your app.

However, Spring Boot won’t start because you haven’t configured the Okta environment variables. You could pass them in on the command line, but it’s easier to specify them in a file.

You can use Docker Compose and its env_file option to specify environment variables.

Copy notes-api/okta.env to src/main/docker/.env.

Remove export at the beginning of each line. It should resemble something like the following after this change:

Create a src/main/docker/app.yml file that configures your app to set environment variables and leverages your existing PostgreSQL container. Make sure to replace the <your-username> placeholder and make the image match what’s in your build.gradle.kts file.

Docker Compose expects the .env file to be in the directory you run docker-compose from, so you have two choices:

  1. Navigate to the src/main/docker directory before running docker-compose
  2. Create a symlink to .env in your root directory: ln -s src/main/docker/.env

If you choose option #1, run:

Option #2 looks like:

Once you’ve verified everything works, commit your changes to Git.

Deploy Your Spring Boot + Angular Container to Docker Hub

Jib makes it incredibly easy to deploy your container to Docker Hub. If you don’t already have a Docker Hub account, you can create one.

Run docker login to log into your account, then use the jib task to build and deploy your image.

Isn’t it cool how Jib makes it so you don’t need a Dockerfile!? ��

To deploy this container to Heroku, create a new Heroku app and add it as a Git remote.

At this point, you can use the PostgreSQL and Okta add-ons you’ve already configured. If you’d like to do this, use addons:attach instead of addons:create in the following commands. Since both add-ons are free, I’m just going to show how to create new ones.

Add PostgreSQL to this app and configure it for Spring Boot using the following commands:

This fine-grained configuration is not necessary when you use Heroku’s buildpacks to deploy your Spring Boot app. It injects scripts that set SPRING_* environment variables for you. In this case, Heroku doesn’t know you’re using Spring Boot since it’s running in a container.

Add Okta to your app.

To see your database and Okta environment variables, run:

Modify the Okta environment variables to remove the _WEB on the two keys that have it.

Run the commands below to deploy the image you deployed to Docker Hub. Be sure to replace the <…> placeholders with your username and app name.

For example, I used:

You can watch the logs to see if your container started successfully.

Once you’ve verified it has started OK, set the Hibernate configuration so it only validates the schema.

Since the Okta Add-on for Heroku configures everything for you, you should be able to open your app, click the Login button, and authenticate!

If you test your Dockerfied Angular + Spring Boot app on, you’ll see it scores an A+!

Heroku is awesome, but sometimes people want more control over their infrastructure. Enter Knative. It’s like Heroku in that it’s a Platform as a Service (PaaS). Knative is built on top of Kubernetes so you can install a number of services with a bit of YAML and kubectl commands.

With Heroku, when companies reach the limitations of the platform, they have to go elsewhere to host their services. With Knative, you can just drop down to Kubernetes. It’s Heroku for Kubernetes in a sense, but you don’t have to switch to a different universe when you need additional functionality.

The Knative website says it’ll make your developers more productive.

Knative components build on top of Kubernetes, abstracting away the complex details and enabling developers to focus on what matters. Built by codifying the best practices shared by successful real-world implementations, Knative solves the “boring but difficult” parts of deploying and managing cloud native services, so you don’t have to.

You’ll need a Google Cloud account for this section. Go to and click Get started for free.

Once you have an account, go to Google Cloud Console and create a new project.

Then, click on the Terminal icon in the top right to open a Cloud Shell terminal for your project.

Enable Cloud and Container APIs:

This command can take a minute or two to complete.

When it’s done, set your default zone and region:

And create a Kubernetes cluster:

You can safely ignore the warnings that result from running this command.

Next, set up a cluster administrator and install Istio.

Now, you should be able to install Knative!

You’ll need a domain to enable HTTPS, so set that up and point it to the cluster’s IP address.

Install cert-manager to automatically provision and manage TLS certificates in Kubernetes.

And configure free TLS certificate issuing with Let’s Encrypt.

Phew! That was a lot of kubectl and YAML, don’t you think?! The good news is you’re ready to deploy PostgreSQL and your Spring Boot app.

The following command can deploy everything, but you’ll need to change the <…> placeholders to match your values first.

Once the deployment has completed, run the command below to change it so Hibernate doesn’t try to recreate your schema on restart.

If everything works correctly, you should be able to run the following command to get the URL of your app.

The result should look similar to this:

You’ll need to add this URL (+ /login/oauth2/code/okta) as a Login redirect URI and a Logout redirect URI in Okta in order to log in.

Then, you’ll be able to log into your app running on Knative! Add a note or two to prove it all works.

Did you know you can run Docker containers on Cloud Foundry? It’s pretty slick.

If you’d like to test it out, you’ll need a Pivotal Web Services account. You’ll also need to install the Cloud Foundry CLI. If you’re using Homebrew, you can use brew install cloudfoundry/tap/cf-cli.

Apps deployed to Cloud Foundry (CF) with the cf push command run in standard CF Linux containers. With Docker support enabled, CF can also deploy and manage apps running in Docker containers.

Then, where secure-notes is a unique name for your app, run the following commands.

At this point, you’ll need to set a number of environment variables so your app can connect to PostgreSQL and Okta. Substitute your values in the <…> placeholders before running the command below.

To get your PostgreSQL URL run the following command where secure-notes is your app name.

You will see a uri at the top of the output that has the URL you’ll need to parse and set as variables below. Make sure to replace postgres:// with jdbc:postgresql:// at the beginning of the datasource URL and extract the credentials for the username and password settings.

Your app, running in Docker, should now be available at http://<your-app-name>

You’ll need to add this URL (+ /login/oauth2/code/okta) as a Login redirect URI and Logout redirect URI on Okta in order to log in.

You’ll also want to configure JPA so it doesn’t recreate the schema on each restart.

Now you should be able to loginlog in and add notes to your heart’s content!

You can also just use a manifest.yml to make it so you don’t have to type all the commands above.

Since most of these environment variables should probably be externally specified, it’s not much gain to use the manifest.yml in this case. Storing secrets in source control is a bad idea!

If you do decide to store everything in manifest.yml, make sure to add it to .gitignore.

With a manifest.yml in place, you can simply run cf push and it’ll do the same thing as the aforementioned cf commands.

Cloud Native Buildpacks is an initiative that was started by Pivotal and Heroku in early 2018. It has a pack CLI that allows you to build Docker images using buildpacks.

Unfortunately, pack doesn’t have great support for monorepos (especially in sub-directories) yet. I was unable to make it work with this app structure.

On the upside, Spring Boot 2.3’s built-in support for creating Docker images works splendidly!

Spring Boot 2.3.0 is now available and with it comes built-in Docker support. It leverages Cloud Native Buildpacks, just like the pack CLI.

Spring Boot’s Maven and Gradle plugins both have new commands:

The Paketo Java buildpack is used by default to create images.

By default, Spring Boot will use your $artifactId:$version for the image name. That is, notes-api:0.0.1-SNAPSHOT. You can override this with an --imageName parameter.

Build and run the image with the commands below.

You should be able to navigate to http://localhost:8080, log in, and add notes.

Pretty neat, don’t you think!? ��

This lengthy tutorial showed you a lot of options when it comes to deploying your Angular and Spring Boot apps with Docker:

  • Build Angular containers with Dockerfile

  • Combine Angular and Spring Boot in a JAR

  • Build Docker images with Jib

  • Build Docker images with Buildpacks

You can find the source code for this example on GitHub at oktadeveloper/okta-angular-spring-boot-docker-example.

As a developer, you probably don’t want to do a series of tutorials to get to a baseline to start a project. The good news is JHipster does everything in this series. It allows you to run your Angular and Spring Boot apps separately, use Kotlin on the server, package your apps together for production, and use Docker for distribution.

To learn more about Angular, Spring Boot, and Docker, see some of our other blog posts.

Follow @oktadev on Twitter for more posts like this one. We also have a YouTube channel you might enjoy. As always, please leave a comment below if you have any questions!

Source link

Write A Comment