How to connect two SCS and a proxy server via a docker-compose.yml file?

We have a project that we have to build two self contained systems - Persons and Projects (some groups have to implement the persons and the others implement the projects- we have to implement the person). For each there is a separate data bank and they have to exchange information with each other. That is working with no problems (I think).

We have a project that we have to build two self contained systems - Persons and Projects (some groups have to implement the persons and the others implement the projects- we have to implement the person). For each there is a separate data bank and they have to exchange information with each other. That is working with no problems (I think).

The problem arises with the docker-compose.yml file :

version: "3.1"
services:
    proxy:
        image: nginx:1.15-alpine
        ports:
          - 8080:80
        volumes:
          - ./proxy/conf/nginx.conf:/etc/nginx/nginx.conf:ro
          - ./proxy/conf/domain.conf:/etc/nginx/domain.conf:ro
        depends_on:
          - projekt
          - person
    # ========================================
    # Falls Sie das Person-SCS implementieren,
    # überschreiben Sie diesen Teil
    persondb:
        #networks:
        #   - default
        image: mysql
        expose:
          - "3306"
        environment:
          - "MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}"
          - "MYSQL_DATABASE=${MYSQL_DATABASE}"
          - "MYSQL_USER=${MYSQL_USER}"
          - "MYSQL_PASSWORD=${MYSQL_PASSWORD}"
        volumes:
          - ./data:/var/lib/mysql
    person:
        #networks:
        #   - default
        build: ./person-scs/.
        depends_on:
          - persondb
        ports:
          - "8080"
            environment:
          - "MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}"
          - "MYSQL_DATABASE=${MYSQL_DATABASE}"
          - "MYSQL_USER=${MYSQL_USER}"
    # ========================================
    # Falls Sie das Projekt-SCS implementieren,
    # überschreiben Sie diesen Teil
    projekt:
        image: hashicorp/http-echo
        command: -listen=:8080 -text="Hello from projekt"
projektdb:
    image: hashicorp/http-echo
    command: -listen=:3306 -text="I am just a dummy"
# ========================================

Don't know if it's relevant, but the Dockefile (inside the Person directory) looks like that:

FROM openjdk:8-jdk-alpine AS build
WORKDIR /app
COPY . ./
RUN ./gradlew --no-daemon --stacktrace clean bootJar

FROM openjdk:8-jre-alpine
RUN apk add --no-cache bash &&
apk update
WORKDIR /app

COPY --from=build /app/build/libs/*.jar app.jar

CMD java -jar app.jar

The whole proxy-part of the docker-compose was given to us by our instructor, as well as the projekt and projektdb parts (because we don't implement the project SCS).

One of the instructions was, that no port other than 8080 will be visible "from the outside" and that we have to call out Person-API via "localhost:8080/person". As of now, when I call the localhost I get a Whitelabel Error Page.

When I ignore the proxy server and implement a docker-compose inside my Person-directory (with the same Dockerfile) I have no problems seeing the localhost:8080/person page and everything works just fine.

The docker-compose file looks like that:

version: "3.1"
services:
database:
networks:
- default
image: mysql
expose:
- "3306"
environment:
- "MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}"
- "MYSQL_DATABASE=${MYSQL_DATABASE}"
- "MYSQL_USER=${MYSQL_USER}"
- "MYSQL_PASSWORD=${MYSQL_PASSWORD}"
volumes:
- ./data:/var/lib/mysql
web:
networks:
- default
build: .
depends_on:
- database
ports:
- "8080:8080"
environment:
- "MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}"
- "MYSQL_DATABASE=${MYSQL_DATABASE}"
- "MYSQL_USER=${MYSQL_USER}"

They gave us no background in writing docker-compose files so I'm not sure what even to Google. Hope someone could give a tip.

WordPress in Docker. Part 1: Dockerization

WordPress in Docker. Part 1: Dockerization

This entry-level guide will tell you why and how to Dockerize your WordPress projects.

This entry-level guide will tell you why and how to Dockerize your WordPress projects.

Dockerize Java App

Dockerize Java App

In this article, we'll provide a brief introduction to Docker and go over what it takes to containerize a Java application.

Dockerize your Java Application

A Dockerfile is a fundamental building block used when dockerizing your Java applications, and it is how you can create a Docker image that can be used to create the containers you need for automatic builds.

Introduction to Dockerfiles

Docker builds images by reading instructions from a Dockerfile. A Dockerfile is a simple text file that contains instructions that can be executed on the command line. Using docker build, you can start a build that executes all of the command-line instructions contained in the Dockerfile.

Common Dockerfile instructions start with RUNENVFROMMAINTAINERADD, and CMD, among others.

  • FROM - Specifies the base image that the Dockerfile will use to build a new image. For this post, we are using phusion/baseimage as our base image because it is a minimal Ubuntu-based image modified for Docker friendliness.

  • MAINTAINER - Specifies the Dockerfile Author Name and his/her email.

  • RUN - Runs any UNIX command to build the image.

  • ENV - Sets the environment variables. For this post, JAVA_HOME is the variable that is set.

  • CMD - Provides the facility to run commands at the start of container. This can be overridden upon executing the docker run command.

  • ADD - This instruction copies the new files, directories into the Docker container file system at specified destination.

  • EXPOSE - This instruction exposes specified port to the host machine.
Writing a Dockerfile for a simple Java application

It is not necessary to write a Dockerfile for OpenJDK in order to run a simple Java application, because you can obtain the official image of OpenJDK from the Docker Hub repository.

Let’s create a Dockerfile for the Oracle JDK, which is not available on Docker Hub.

To begin this process, create a new folder and then create a file in it named “Dockerfile” with the following content.

# Dockerfile

FROM phusion/baseimage:0.9.17

MAINTAINER Author Name <[email protected]>

1. Update the package repository

RUN echo "deb http://archive.ubuntu.com/ubuntu trusty main universe" > /etc/apt/sources.list

RUN apt-get -y update

2. Install python-software-properties

This enables add-apt-repository for use later in the process.

RUN DEBIAN_FRONTEND=noninteractive apt-get install -y -q python-software-properties software-properties-common

3. Install Oracle Java 8

ENV JAVA_VER 8
ENV JAVA_HOME /usr/lib/jvm/java-8-oracle

RUN echo 'deb http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main' >> /etc/apt/sources.list &&
    echo 'deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main' >> /etc/apt/sources.list &&
  apt-key adv --keyserver keyserver.ubuntu.com --recv-keys C2518248EEA14886 &&
  apt-get update &&
  echo oracle-java${JAVA_VER}-installer shared/accepted-oracle-license-v1-1 select true | sudo /usr/bin/debconf-set-selections &&
  apt-get install -y --force-yes --no-install-recommends oracle-java${JAVA_VER}-installer oracle-java${JAVA_VER}-set-default &&
  apt-get clean &&
  rm -rf /var/cache/oracle-jdk${JAVA_VER}-installer

4. Set Oracle Java as the default Java

RUN update-java-alternatives -s java-8-oracle

RUN echo "export JAVA_HOME=/usr/lib/jvm/java-8-oracle" >> ~/.bashrc

5. Clean Up APT when finished

RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

6. Use baseimage-docker’s init system

CMD ["/sbin/my_init"]

View the complete Dockerfile

# Dockerfile

FROM phusion/baseimage:0.9.17

MAINTAINER Author Name <[email protected]>

RUN echo "deb http://archive.ubuntu.com/ubuntu trusty main universe" > /etc/apt/sources.list

RUN apt-get -y update

RUN DEBIAN_FRONTEND=noninteractive apt-get install -y -q python-software-properties software-properties-common

ENV JAVA_VER 8
ENV JAVA_HOME /usr/lib/jvm/java-8-oracle

RUN echo 'deb http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main' >> /etc/apt/sources.list &&
    echo 'deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main' >> /etc/apt/sources.list &&
  apt-key adv --keyserver keyserver.ubuntu.com --recv-keys C2518248EEA14886 &&
  apt-get update &&
  echo oracle-java${JAVA_VER}-installer shared/accepted-oracle-license-v1-1 select true | sudo /usr/bin/debconf-set-selections &&
  apt-get install -y --force-yes --no-install-recommends oracle-java${JAVA_VER}-installer oracle-java${JAVA_VER}-set-default &&
  apt-get clean &&
  rm -rf /var/cache/oracle-jdk${JAVA_VER}-installer

RUN update-java-alternatives -s java-8-oracle

RUN echo "export JAVA_HOME=/usr/lib/jvm/java-8-oracle" >> ~/.bashrc

RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

CMD ["/sbin/my_init"]

Building the image from the Dockerfile

Now that we have written a Dockerfile, we can build the corresponding Docker image.

To build the image, start with the following command:

$ docker build -f Dockerfile -t demo/oracle-java:8 .
  • -f specifies the Dockerfile. This can be skipped if the filename used at the beginning of this process is Dockerfile.

  • -t specifies the name of the image. The name demo/oracle-java, and the 8 after the colon, specify the image tag. The tag 8 is used because we are using Java 8. This can be changed to any tag name that makes sense.

NOTE: Do not forget the .(dot) at the end of command; it specifies the context of the build. The .(dot) at the end of the command specifies the current directory. The files and directories of current directory will be sent to Docker daemon as a build artifact.

We have built our Java 8 image successfully, now we need to test it using sample Java application.

Testing the Image

Create a project folder and then create a file called Main.java inside this folder with following content:

public class Main
{
   public static void main(String[] args) {
    System.out.println("Hello, World");
  }
}

Now execute the following commands from the current project directory.

  • To compile your Main.java file.
$ docker run --rm -v $PWD:/app -w /app demo/oracle-java:8 javac Main.java
  • To run your compiled Main.class file.
$ docker run --rm -v $PWD:/app -w /app demo/oracle-java:8 java Main

output should be displayed.

Hello, World 

You have seen in the above example that we used the Oracle Java image to successfully run a sample Java application.

If you need to use the OpenJDK for your application, you don’t always need to write a Dockerfile and build an image. You can use the official Docker Hub repository version of Java.

Run the following commands to run your application using OpenJDK.

$ docker run --rm -v $PWD:/app -w /app java:8 javac Main.java

$ docker run --rm -v $PWD:/app -w /app java:8 java Main


Writing a Dockerfile for a Maven-based Java application

If you’re using the OpenJDK with Maven, you don’t necessarily need to write a Dockerfile because you can use the official Docker Hub repository’s version of Maven. However, if you’re using the Oracle JDK with Maven, then you’ll need to write your own Dockerfile.

We will use the demo/oracle-jdk:8 image as our base image because we have built this image in our previous example.

1. Create the Dockerfile

# Dockerfile
FROM demo/oracle-java:8

ENV MAVEN_VERSION 3.3.9

RUN mkdir -p /usr/share/maven
  && curl -fsSL http://apache.osuosl.org/maven/maven-3/$MAVEN_VERSION/binaries/apache-maven-$MAVEN_VERSION-bin.tar.gz
  | tar -xzC /usr/share/maven --strip-components=1
 && ln -s /usr/share/maven/bin/mvn /usr/bin/mvn

ENV MAVEN_HOME /usr/share/maven

VOLUME /root/.m2

CMD ["mvn"] 

In this Dockerfile we have used the command VOLUME. This command is used to expose to the host machine the volume from the container. We can map this volume to any host directory.

2. Build the Docker image

Build the docker image from the above Dockerfile using this command:

$ docker build -f Dockerfile -t demo/maven:3.3-jdk-8 .

This will build an image with the name of demo/maven and tag of 3.3-jdk-8. Name and tag your images clearly so that you can easily identify each image.

3. Run a test application

Run a test Maven application using this image that we created.

If you don’t have a Maven project, create one using this command:

$ docker run -it --rm -v "$PWD":/app -w /app demo/maven:3.3-jdk-8 mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -Dinte

This will create a Maven project in the current directory under the my-app directory.

4. Build the project and test the JAR file

Go to the project directory.

$ cd my-app

Build the project.

$ docker run -it --rm -v "$PWD":/app -w /app demo/maven:3.3-jdk-8 mvn package

Test the newly compiled and packaged JAR with the following command.

$ docker run -it --rm -v "$PWD":/app -w /app demo/maven:3.3-jdk-8 java -cp target/my-app-1.0-SNAPSHOT.jar com.mycompany.app.App

This should print the following output:

Hello World!


Write a Dockerfile for Spring MVC web application

There are two approaches we can take for Spring-based applications.

  1. Use the existing Maven-based image as the base image and install Tomcat on it to run the web application.

  2. Use the existing Maven-based image to only compile and package the application. And then use a different Tomcat-based Docker container to deploy the application.

We’ll cover both approaches next.

Install Tomcat on the existing Maven-based image

Create an empty directory and add a Dockerfile inside it with the following content.

# Dockerfile
FROM demo/maven:3.3-jdk-8
MAINTAINER Author <[email protected]>
RUN apt-get update &&
  apt-get install -yq --no-install-recommends wget pwgen ca-certificates &&
  apt-get clean &&
  rm -rf /var/lib/apt/lists/*
ENV TOMCAT_MAJOR_VERSION 8
ENV TOMCAT_MINOR_VERSION 8.0.11
ENV CATALINA_HOME /tomcat

1. Install Tomcat

RUN wget -q https://archive.apache.org/dist/tomcat/tomcat-${TOMCAT_MAJOR_VERSION}/v${TOMCAT_MINOR_VERSION}/bin/apache-tomcat-${TOMCAT_MINOR_VERSION}.tar.gz && 
wget -qO- https://archive.apache.org/dist/tomcat/tomcat-${TOMCAT_MAJOR_VERSION}/v${TOMCAT_MINOR_VERSION}/bin/apache-tomcat-${TOMCAT_MINOR_VERSION}.tar.gz.md5 | md5sum -c - &&
tar zxf apache-tomcat-.tar.gz &&
  rm apache-tomcat-
.tar.gz &&
  mv apache-tomcat* tomcat

ADD create_tomcat_admin_user.sh /create_tomcat_admin_user.sh
RUN mkdir /etc/service/tomcat
ADD run.sh /etc/service/tomcat/run
RUN chmod +x /*.sh
RUN chmod +x /etc/service/tomcat/run

EXPOSE 8080

2. Use baseimage-docker’s init system

CMD ["/sbin/my_init"]

3. Create the Tomcat admin user

Create a file called createtomcatadmin_user.sh in the same directory with following content:

!/bin/bash

if [ -f /.tomcat_admin_created ]; then
  echo "Tomcat 'admin' user already created"
  exit 0
fi

4. Generate Password

Continue to add the following script to generate a password.

PASS=${TOMCAT_PASS:-$(pwgen -s 12 1)}
_word=$( [ ${TOMCAT_PASS} ] && echo "preset" || echo "random" )

echo "=> Creating an admin user with a ${_word} password in Tomcat"
sed -i -r 's/</tomcat-users>//' ${CATALINA_HOME}/conf/tomcat-users.xml
echo '<role rolename="manager-gui"/>' >> ${CATALINA_HOME}/conf/tomcat-users.xml
echo '<role rolename="manager-script"/>' >> ${CATALINA_HOME}/conf/tomcat-users.xml
echo '<role rolename="manager-jmx"/>' >> ${CATALINA_HOME}/conf/tomcat-users.xml
echo '<role rolename="admin-gui"/>' >> ${CATALINA_HOME}/conf/tomcat-users.xml
echo '<role rolename="admin-script"/>' >> ${CATALINA_HOME}/conf/tomcat-users.xml
echo "<user username="admin" password="${PASS}" roles="manager-gui,manager-script,manager-jmx,admin-gui, admin-script"/>" >> ${CATALINA_HOME}/conf/tomcat-users.xml
echo '</tomcat-users>' >> ${CATALINA_HOME}/conf/tomcat-users.xml
echo "=> Done!"
touch /.tomcat_admin_created

echo "========================================================================"
echo "You can now configure to this Tomcat server using:"
echo ""
echo "  admin:${PASS}"
echo ""
echo "========================================================================"

This file creates the Tomcat admin user. Add one more file in the same directory named as run.sh with following content. This will call the create users file and then reload the Tomcat server.

!/bin/bash

if [ ! -f /.tomcat_admin_created ]; then
  /create_tomcat_admin_user.sh
fi

exec ${CATALINA_HOME}/bin/catalina.sh run

5. Build and Test the Docker Image

Build the docker image using following command.

$ docker build -f Dockerfile -t demo/spring:maven-3.3-jdk-8 .

Test the image.

Here is the sample Spring Maven-based project that you can use for testing. You can download the zip or clone it by using the following command:

$ git clone  https://github.com/atifsaddique211f/spring-maven-sample.git

Go to the project directory:

$ cd spring-maven-sample

Run the following command to build and package the project:

$ docker run -it --rm -v "$PWD":/app -w /app demo/spring:maven-3.3-jdk-8 mvn clean install

The above command will create a war file at target/springwebapp.war.

Copy this war file into the Tomcat webapps directory:

$ docker run -it -d --name spring -p 8080:8080 -v "$PWD":/app demo/spring:maven-3.3-jdk-8 bash -c "cp /app/target/springwebapp.war /tomcat/webapps/ & /tomcat/bin/catalina.sh run"

The above command runs a container named spring in detached mode. It also provides mapping from the Docker container port 8080 to host machine port 8080.

You can access your web application at the following url in the browser.http://localhost:8080/springwebapp/car/add.

This will show a sample form to add a car.

Since the Docker container is run in detached mode, it will keep running in the background. You can check the running container using following command:

$ docker ps

To check all running and non-running containers use this command:

$ docker ps -a

So to stop our Spring application container, we need to execute following command:

$ docker rm -vf spring
Run Spring app with a different Tomcat Docker image

Clone the same sample project:

$ git clone  https://github.com/atifsaddique211f/spring-maven-sample.git

Go to the project directory:

$ cd spring-maven-sample

Create a Dockerfile with following content:

# Dockerfile
FROM tomcat:8

ADD target/*.war /usr/local/tomcat/webapps/

Build and package and the project:

$ docker run -it --rm -v "$PWD":/app -w /app demo/maven:3.3-jdk-8 mvn clean install

Build the Dockerfile:

$ docker build -f Dockerfile -t demo/tomcat:8 .

Run the application by executing this command:

$ docker run --rm -p 8080:8080 demo/tomcat:8

Now you can access your web application at the following url in the browser.http://localhost:8080/springwebapp/car/add.

This will show a sample form to add a car.

To stop the application, press Ctrl + C.

Conclusion

In this article, we’ve covered the fundamentals of how to go about dockerizing your Java application. We went over the basics of what a Dockerfile is, and how to create a Dockerfile for a simple Java application, a Maven-based Java application, and a Spring MVC web application. We’ve also learned how to build the Dockerfiles into an image, and to run the image to launch a container.

Thanks For Visiting, Keep Visiting.

This post was originally published here

Get Jibby With Java, Docker, and Spring Boot

Get Jibby With Java, Docker, and Spring Boot

Get Jibby With Java, Docker, and Spring Boot Andrew Hughes. Docker is a very popular system for containerizing applications. Containerization packages the executable

Docker is a very popular system for containerizing applications. Containerization packages the executable code along with the runtime environment in deployable virtual images using a repeatable, automatable process.

In the world of cloud-based development and microservices, where a single application can be spread across hundreds of servers in various networks with complex port configurations, the ability to automate the deployment of “units” of code is super helpful. The ability to control the execution environment also offers advantages: managing variables like OS version, disk size, available memory, port configuration, etc… Containerization helps avoid unexpected conflicts when OS libraries create unexpected conflicts or bugs on update.

All of this control often comes at the cost of complexity, however. Creating and maintaining dockerfiles can be time-consuming. Jib to the rescue! Jib allows you to easily Dockerize Spring Boot projects, using plugins for Maven and Gradle. Beyond just ease of containerization, Jib also takes advantage of image layering and registry caching to speed up builds by only re-building the parts of an application that have changed.

In this tutorial, you will build a simple Spring Boot REST API and use Jib to dockerize it. You will use OAuth 2.0 and Okta to protect the resource server.

Let’s get started!

Install Dependencies

For this tutorial, you need to install a few dependencies. First, you’ll need Java. I’ve written the tutorial for Java 11, but it should be backward compatible with Java 8. If you don’t have Java installed, go to the AdoptOpenJDK website and install it. On a Mac, you can also use Homebrew.

The next tool you’ll need is HTTPie, a simple command-line HTTP client. Please follow instructions on their website to install it.

You’ll also need a free developer account with Okta. Okta is a SaaS (software-as-service) identity management provider. We make it easy to add features like single sign-on, social login, and OAuth 2.0 to your application. Sign up for an account on our website if you haven’t already.

Finally, you’ll need Docker Desktop. This allows you to quickly and easily run local Docker images on your computer. It’s great for testing, development, and tutorials like this. Check out the Docker Desktop website for installation instructions.

This tutorial uses Gradle as a build system, which you can install locally from their website, but it’s not required to install since the project starter will include a Gradle wrapper. But if you want to install Gradle locally, or just want to learn more about the project, check out the Gradle website.

You’ll also need some sort of code editor or IDE. I like Intellij IDEA Community Edition for Java development. It’s free and awesome. But there are tons of other options as well.

Use Spring Initializr to Download Initial Project

You installed HTTPie, right? In this section, you’re going to use it to command Spring Initializr to create and download your initial project.

From a command line:

http https://start.spring.io/starter.zip \ dependencies==web,okta \ groupId==com.okta.spring-docker.demo \ packageName==com.okta.spring-docker.demo \ type==gradle-project \ -d 

You can read about all of the parameters available on Spring Initializr’s REST API on the Spring Initializr GitHub page. The important points are that you specified a Gradle project, included a couple of dependencies, and specified your group and package information.

The two dependencies are web and okta. web is short for spring-boot-starter-web, which allows Spring Boot to serve HTTP requests. okta is short for Okta’s Spring Boot Starter, which simplifies adding Okta OAuth to Spring applications. If you’d like to learn more about this project, check out the Okta Spring Boot GitHub page.

The command above downloads a file named demo.zip. Unzip it somewhere and open it in the editor or IDE of your choice:

unzip demo.zip -d spring-boot-docker 

This fully functioning Spring Boot app defines an empty Spring Boot application without any controllers, so it doesn’t do much. Before you fix that, you need to add one more dependency to the build.gradle file.

Just Jib it!

To add Jib to the Gradle project, simply add the plugin to the build.gradle file. If you want to dig in deeper, take a look at the Introducing Jib blog post or Jib’s GitHub page.

Add id 'com.google.cloud.tools.jib' version '1.3.0' to the plugins closure at the top of the build.gradle file, like so:

plugins { id 'org.springframework.boot' version '2.1.5.RELEASE' id 'java' id 'com.google.cloud.tools.jib' version '1.3.0' // <-- ADD ME } 

If you open a shell and navigate to the project root, you can now run ./gradlew tasks and see the tasks that the new plugin has added to the project.

Jib tasks --------- jib - Builds a container image to a registry. jibBuildTar - Builds a container image to a tarball. jibDockerBuild - Builds a container image to a Docker daemon. 

In this example, you will be using the jibDockerBuild tasks. This pushes the image to the Docker daemon run by Docker Desktop. This is great for local development and testing.

More often in a larger production environment, you would push to a container registry using jib. Jib can easily push to a variety of container registries, such as Google Container Registry, Amazon Elastic Container Registry, Docker Hub Registry, and Azure Container Registry.

Note that Docker Desktop has to be running in order for the jibDockerBuild task to work. Go ahead and start Docker Desktop if it isn’t already running.

Add a Web Controller and Configure Security

In order for your application to respond to HTTP requests, you need to add a controller. Add a new file called WebController.java in the directory src/main/java/com/okta/springdocker/demo.

package com.okta.springdocker.demo; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController public class WebController { @RequestMapping("/") public String home() { return "Welcome!"; } } 

You also need to configure the security settings for this project. For the moment, you’ll want to allow all requests, so update your DemoApplication.java file to the following:

package com.okta.springdocker.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Configuration static class OktaOAuth2WebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests().anyRequest().permitAll(); } } } 

Try it Out!

Build the project and push the Docker image to the local registry using the following command (from the project root dir):

./gradlew build jibDockerBuild 

After this completes, you should be able to list the Docker images:

docker images 

And see your application image in the local Docker registry:

REPOSITORY TAG IMAGE ID CREATED SIZE demo 0.0.1-SNAPSHOT 490d12302a6d 49 years ago 146MB 

To run your Spring Boot app, use the following command:

docker run --publish=8080:8080 demo:0.0.1-SNAPSHOT 

This command specifies the image repository and tag as well as instructing Docker to map port 8080 in the image to local port 8080.

Now you can use HTTPie to run a simple request:

http :8080 

And you should see:

HTTP/1.1 200 Cache-Control: no-cache, no-store, max-age=0, must-revalidate Content-Length: 8 Content-Type: text/plain;charset=UTF-8 ... Welcome! 

Sweet! So, at this point, you’ve created a simple Spring Boot application with a basic web controller and overridden the default security settings to allow all requests. You’ve also created a Docker image, pushed it to your local Docker registry, and run the image - all without a Docker file!

The next step is to add JSON Web Token (JWT) authentication using OAuth 2.0 and OpenID Connect (OIDC). The provider you’re going to use for this tutorial is Okta.

Create an OIDC Application

Create an OIDC application on Okta using your developer account. If you don’t have one, signup and return to this tutorial after activating your account.

Sign in to the Okta developer console. If this is your first time to log in, you may need to click the Admin button in the upper right-hand corner to get to the developer console.

Next, you will create an OpenID Connect (OIDC) application. OAuth 2.0 along with OpenID Connect is the protocol spec Okta implements to allow your application to handle authentication and authorization securely with the Okta servers.

Click on the Application top menu. Click the Add Application button.

Select application type Web.

Click Next.

Give the app a name. I named mine Spring Boot Docker. The OIDC Debugger website allows you to create access tokens you can use to access your app with HTTPie. You need to add a login redirect URI and allow implicit flow for this website to work.

Under Login redirect URIs, add a new URI: [https://oidcdebugger.com/debug](https://oidcdebugger.com/debug "https://oidcdebugger.com/debug").

Under Grant type allowed, check the box next to Implicit (Hybrid).

The rest of the default values will work.

Click Done.

Leave the page open and take note of the Client ID. You’ll need it in a moment.

You’ll also want to know the Issuer URI from Okta. If you go to API in the top menu and click on Authorization Servers, you’ll see the default auth server. By default, all your OIDC apps are added to this auth server. The Issuer URI will be something like this: [https://dev-123456.okta.com/oauth2/default](https://dev-123456.okta.com/oauth2/default "https://dev-123456.okta.com/oauth2/default").

You won’t need to do anything with it since this tutorial uses the Okta Spring Boot Starter and default values. The audience value, api://default, can be customized for more complex or custom applications.

Configure Spring Boot App for OAuth

First, rename the src/main/resources/application.properties file to application.yml. Then add in the following values (filling in your Client ID and Okta URL):

okta: oauth2: issuer: https://{yourOktaDomain}/oauth2/default client-id: {yourClientID} 

If you were not using the Okta Spring Boot Starter, this configuration would be a little more extensive, but because you’re using the starter, it sets many defaults for you and simplifies setup.

Next, update the security configuration to use OAuth 2.0 and JWT authentication. In the DemoApplication.java file, update the configure(HttpSecurity http) method in the OktaOAuth2WebSecurityConfigurerAdapter static class to match the following:

@Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests().anyRequest().authenticated() .and() .oauth2ResourceServer().jwt(); } 

Finally, change your WebController.java file to match the following:

package com.okta.springdocker.demo; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.security.Principal; @RestController public class WebController { @RequestMapping("/") public String home(@AuthenticationPrincipal JwtAuthenticationToken jwtAuthenticationToken) { return "Welcome " + jwtAuthenticationToken.getName() + "!"; } @RequestMapping("/info") public String info(@AuthenticationPrincipal JwtAuthenticationToken jwtAuthenticationToken) { return jwtAuthenticationToken.toString(); } } 

You could have left the WebController the same. This doesn’t affect authentication. The changes demonstrate how to get a little information about the authenticated party from Spring Security.

Run the App Again, with OAuth 2.0!

Stop the previous process if it’s still running. You should be able to Control-C from the shell where you ran the docker run command. If that doesn’t work, you can use the following command to stop all running docker containers:

docker stop $(docker ps -a -q) 

From a terminal at the project root, run the following command to rebuild the project and the docker image:

./gradlew build jibDockerBuild 

Once this process completes, run the image:

docker run --publish=8080:8080 demo:0.0.1-SNAPSHOT 

Use HTTPie to make a request:

http :8080 

You’ll get:

HTTP/1.1 401 Cache-Control: no-cache, no-store, max-age=0, must-revalidate Content-Length: 0 ... 

Success! Of sorts. You still need to get a valid token. Fortunately, OpenID Connect debugger allows you to do that easily (remember when you added this URL to the list of authorized redirect URLs in your OIDC app on Okta?).

In a browser, go to https://oidcdebugger.com.

Update the following values:

  • Authorize URI: https://{yourOktaDomain}/oauth2/default/v1/authorize
  • Client ID: {yourClientID}
  • State: Any value really, I used This is the state

Scroll down and click Send Request.

Copy the token from the success screen and save it in a shell variable:

TOKEN=eyJraWQiOiJxMm5rZmtwUDR... 

Now you can use the JWT in your request:

http :8080 "Authorization: Bearer $TOKEN" 

And see something like:

HTTP/1.1 200 Cache-Control: no-cache, no-store, max-age=0, must-revalidate Content-Length: 33 ... Welcome [email protected]! 

If you look back in the WebController class, you can see where we used dependency injection to get the JwtAuthenticationToken, which got the authenticated name:

"Welcome " + jwtAuthenticationToken.getName() + "!"; 

You can also try the /info endpoint (in the JwtAuthenticationToken class) for more detailed information.

Learn More about Docker and Spring Boot

In this tutorial, you learned how to use Jib to easily Dockerize Spring Boot applications. You also used Okta and OAuth 2.0 / OIDC to protect this application. You generated a JWT using the OIDC Debugger and tested the authentication using the command line.

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

Further reading:

Publish a Docker container from Bitbucket to Google Cloud Container Registry

Kubernetes Cluster Setup With Jelastic

How To Set Up Laravel App on Docker, With NGINX and MySQL

Developing WordPress Sites With Docker

Build Falcon API Framework on Docker