DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Running a Java App With MySQL in Any Docker Environment
  • Spring Cloud Stream: A Brief Guide
  • Automate Spring Boot App Deployment With GitLab CI and Docker
  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS

Trending

  • A Developer's Guide to Mastering Agentic AI: From Theory to Practice
  • How to Convert XLS to XLSX in Java
  • Measuring the Impact of AI on Software Engineering Productivity
  • Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
  1. DZone
  2. Coding
  3. Frameworks
  4. How To: Docker With Spring Boot

How To: Docker With Spring Boot

This tutorial will show you how to build and run a simple web application into the Docker-compatible image using Cloud Native Buildpacks support, from Spring Boot 2.3.0.

By 
Ruslan Zaharov user avatar
Ruslan Zaharov
·
Feb. 12, 21 · Tutorial
Likes (9)
Comment
Save
Tweet
Share
15.0K Views

Join the DZone community and get the full member experience.

Join For Free

If you are reading this, there is no doubt you have heard of Docker. Living up to the hype, Docker has become the relative standard for DevOps operations. Its ability to simplify deployments and testing by creating efficient and immutable images of the applications working in their own silo has greatly helped with its popularity. The majority of Docker’s attention can be attributed to its improved efficiency regarding placement of applications—making tech central for cloud applications. 

By unifying application development Docker makes the target environment part of your app in the form of a container rather than forcing you to prepare its environment on each machine. This means you no longer have to deal with conflicting library versions or overlapping network posts. Built images are immutable, allowing your application to work the same way locally, on a team member’s computer, or the cloud. In addition to this, it is possible to run many instances of the container on the same machine, which helps to increase the density of deployments, and in turn, brings down costs. 

This tutorial will show you how to build and run a simple web application into the Docker-compatible image using Cloud Native Buildpacks support, from Spring Boot 2.3.0.

Prerequisites:

  • Java 11+
  • Unix-like shell
  • Docker installed
  • Okta CLI installed

Bootstrap a Secure Spring Boot Application

Start by creating a Spring Boot application using Spring Boot Initializr. This can be done via the web interface or using a handy curl command:

Java
 




x


 
1
curl https://start.spring.io/starter.tgz -d dependencies=web,okta \
2
   -d bootVersion=2.4.1 \
3
   -d groupId=com.okta \
4
   -d artifactId=demospringboot \
5
   -d type=gradle-project \
6
   -d language=kotlin \
7
   -d baseDir=springboot-docker-demo | tar -xzvf -



This command requests that Spring Boot Initializr generate an application that uses the Gradle build system and Kotlin programming language. It also configures dependencies on Spring Web and Okta. The created project is automatically unpacked to the springboot-docker-demo directory.

Update your main application class to allow unauthenticated access in WebSecurityConfigurerAdapter. While in there, add a controller that welcomes the user. It’s safe to put everything in a single file src/main/kotlin/com/okta/demospringboot/DemoApplication.kt:

Java
 




xxxxxxxxxx
1
30


 
1
package com.okta.demospringboot
2

          
3
import org.springframework.boot.autoconfigure.SpringBootApplication
4
import org.springframework.boot.runApplication
5
import org.springframework.security.config.annotation.web.builders.HttpSecurity
6
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
7
import org.springframework.context.annotation.Configuration
8
import org.springframework.web.bind.annotation.RequestMapping
9
import org.springframework.web.bind.annotation.RestController
10
import java.security.Principal
11

          
12
@SpringBootApplication
13
class DemoApplication
14

          
15
fun main(args: Array<String>) {
16
    runApplication<DemoApplication>(*args)
17
}
18

          
19
@Configuration
20
class OktaOAuth2WebSecurityConfigurerAdapter: WebSecurityConfigurerAdapter() {
21
    override fun configure(http: HttpSecurity) {
22
        http.authorizeRequests().anyRequest().permitAll()
23
    }
24
}
25

          
26
@RestController
27
class WebController {
28
    @RequestMapping("/")
29
    fun home(user: Principal?) = "Welcome, ${user?.name ?: "guest"}!"
30
}



Run Your Spring Boot Application

Start your application in the project folder via the command line:

Java
 




xxxxxxxxxx
1


 
1
./gradlew bootRun


Then, open a browser at http://localhost:8080. Your web application greets the guest user:

Build a Spring Boot Docker Image

Since version 2.3.0, Spring Boot has supported Cloud Native Buildpacks. It has become straightforward to deploy a web service to the popular clouds using Buildpacks due to the mass adoption of this technology.

Build your application and send the image to the local Docker daemon:

Java
 




xxxxxxxxxx
1


 
1
./gradlew bootBuildImage --imageName=springbootdemo



Next, start your containerized web application with Docker:

Java
 




xxxxxxxxxx
1


 
1
docker run -it -p8080:8080 springbootdemo



As expected, your web application will be available on http://localhost:8080.

Secure Your Spring Boot Application in Docker

User management is never an easy task and, most certainly, is not the main objective of your application. Okta is an identity provider that helps you to take care of routine work such as implementing OAuth 2.0, social login, and SSO (Single Sign-On). It’s very developer-friendly, and it has excellent integration with different frameworks, including Spring Boot.

Start with installing the Okta CLI tool - it’s a real time saver for developers.

  1. Create your free developer account with Okta, no credit card required:

    Java
     




    xxxxxxxxxx
    1


     
    1
    okta register
    2
    
                
    3
     ...(provide registration details)...
    4
     ...
    5
     To set your password open this link:
    6
     https://dev-xxxxxxxxxxxx.okta.com/welcome/ABCDEFG


    Don’t forget to set your password using the link above!
  2. Create an Okta application. In your project directory, execute:
    Java
     




    xxxxxxxxxx
    1


     
    1
    okta apps create --redirect-uri http://localhost:8080/login/oauth2/code/okta


    The Okta CLI will prompt you for an application name—choosing the default is OK. Next, select 1 (Web), then 1 (Okta Spring Boot Starter). Accept defaults, the Okta CLI will configure the default login redirect URI (http://localhost:8080/login/oauth2/code/okta) and logout redirect URI (http://localhost:8080). Don’t worry, you can change these values later if something needs to be adjusted.


    3. When an application successfully created, its configuration is saved in the current folder, in a .okta.env file.

    Java
     




    xxxxxxxxxx
    1


     
    1
    cat .okta.env
    2
    export OKTA_OAUTH2_ISSUER="https://dev-xxxxxx.okta.com/oauth2/default"
    3
    export OKTA_OAUTH2_CLIENT_SECRET="yyy"
    4
    export OKTA_OAUTH2_CLIENT_ID="zzz"


    You’ll need to run source .okta.env to set these values as environment variables. If you’re on Windows, rename the file to .okta.bat and change export to set. These parameters need to be injected into the application to enable OAuth flows for authentication and authorization.

    NOTE: make sure you never check in credentials to your source control system.


    Configure Spring Security to Lock Down Access

    Previously, your webpage was accessible for everyone. To allow access for authorized users only, update the Spring Security configuration in src/main/kotlin/com/okta/demospringboot/DemoApplication.kt:

    Java
     




    xxxxxxxxxx
    1


     
    1
    @Configuration
    2
    class OktaOAuth2WebSecurityConfigurerAdapter: WebSecurityConfigurerAdapter() {
    3
        override fun configure(http: HttpSecurity) {
    4
            http.authorizeRequests().anyRequest().authenticated();
    5
        }
    6
    }


    That’s it. The Okta Spring Boot Starter takes care of the rest!

    Rebuild the application again:

    Java
     




    xxxxxxxxxx
    1


     
    1
    ./gradlew bootBuildImage --imageName=springbootdemo


    The --imageName parameter allows specifying an image name. Without it, the name would be something like appName:0.0.1-SNAPSHOT.

    Start Spring Boot Application in Docker

    When your application starts, the Okta module reads environment variables to configure security in your application. Start your application with your values set:

    Java
     




    xxxxxxxxxx
    1


     
    1
    docker run -it -p8080:8080 \
    2
        -e OKTA_OAUTH2_ISSUER="https://dev-xxxxxx.okta.com/oauth2/default" \
    3
        -e OKTA_OAUTH2_CLIENT_SECRET="yyyyyyyyyyyyyyyyyyy" \
    4
        -e OKTA_OAUTH2_CLIENT_ID="zzzzzzzzzzzzzzzz" \
    5
        springbootdemo


    The argument -e allows to set an environment variable for the application running inside your container and -p maps container’s point to the localhost.

    Now, head over to http://localhost:8080, and you’ll be asked to log in using Okta’s standard form. Enter your login credentials and, upon successful sign-in, your web browser will be redirected to the main page, displaying a welcoming message.

    Create a .envfile in the root of the project and set desirable environment variables:

    Java
     




    xxxxxxxxxx
    1


     
    1
    OKTA_OAUTH2_ISSUER=https://{yourOktaDomain}/oauth2/default
    2
    OKTA_OAUTH2_CLIENT_SECRET={yourClientSecret}
    3
    OKTA_OAUTH2_CLIENT_ID={yourClientId}


    Always be extra careful with credentials - avoid leaking them to the version control system even for the pet project. Add .env to .gitignore.
    Java
     




    xxxxxxxxxx
    1


     
    1
    echo ".env" >> .gitignore


    Run Docker providing your .env file via --env-fileargument
    Java
     




    xxxxxxxxxx
    1


     
    1
    docker run -it -p8080:8080 --env-file .env springbootdemo


    Looks much cleaner, doesn’t it?

    Deploy Spring Boot + Docker to Heroku

    If you’d like to deploy your dockerized Spring Boot app to Heroku, you’ll need to use Heroku Buildpacks. This is because the Paketo buildpacks refuse to allocate heap on containers smaller than 1GB of RAM. A free Heroku dyno has 512MB.

    First, you’ll need to add the following to src/main/resources/application.properties so Spring Boot uses Heroku’s PORT environment variable.

    Java
     




    xxxxxxxxxx
    1


     
    1
    server.port=${PORT:8080}


    Then, build your image with --builder heroku/spring-boot-buildpacks:

    Java
     




    xxxxxxxxxx
    1


     
    1
    ./gradlew bootBuildImage --imageName=springbootdemo --builder heroku/spring-boot-buildpacks


    Create an app on Heroku:

    Java
     




    xxxxxxxxxx
    1


     
    1
    heroku create


    Log in to Heroku’s container registry and push your app:

    Java
     




    xxxxxxxxxx
    1


     
    1
    heroku container:login
    2
    docker tag springbootdemo registry.heroku.com/<your-app-name>/web
    3
    docker push registry.heroku.com/<your-app-name>/web


    Set your Okta app settings as environment variables:

    Java
     




    xxxxxxxxxx
    1


     
    1
    heroku config:set \
    2
      OKTA_OAUTH2_ISSUER="https://{yourOktaDomain}/oauth2/default" \
    3
      OKTA_OAUTH2_CLIENT_ID="{clientId}" \
    4
      OKTA_OAUTH2_CLIENT_SECRET="{clientSecret}"


    Next, release your container and tail the logs.

    Java
     




    xxxxxxxxxx
    1


     
    1
    heroku container:release web
    2
    heroku logs --tail


    You’ll need to update your Okta OIDC app to have your Heroku app’s redirect URIs as well.

    • Login redirect URI: https://<your-app-name>.herokuapp.com/login/oauth2/code/okta
    • Logout redirect URI: https://<your-app-name>.herokuapp.com

    Run heroku open to open your app and sign in.

    Learn More About Docker, Spring Boot, and Buildpacks

    In this brief tutorial, you created a secure Spring Boot application and packaged it with Docker. You configured Okta as an OAuth 2.0 provider, built an image into your local Docker daemon, and learned how to run your app in Docker. This bootstrap project is a great starting point for your next cloud-native project.

    You can find the source code for this example on GitHub.

    Follow us for more great content and updates from our team! You can find us on Twitter, Facebook, subscribe to our YouTube Channel or start the conversation below!

    Changelog:

    • Dec 31, 2020: Updated post to add Heroku instructions, since it requires another buildpack. Thanks for the idea, Maurizio! See the code changes in the example on GitHub. Changes to this post can be viewed in oktadeveloper/okta-blog#514.
Spring Framework Spring Boot Docker (software) application Java (programming language) Spring Security app Web application Web Service

Published at DZone with permission of Ruslan Zaharov. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Running a Java App With MySQL in Any Docker Environment
  • Spring Cloud Stream: A Brief Guide
  • Automate Spring Boot App Deployment With GitLab CI and Docker
  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!