Skip to main content
docker-logo

Spring Boot with Docker

spring-boot-and-docker

Overview

We already discussed how to develop REST web service using the Spring Boot. There are a couple of tutorials that related to Spring Boot.

Building a simple REST Service with Spring Boot

Spring Boot REST web service – Spring Data and MySQL

In this tutorial, we are going to walk through how to containerize a spring boot application using the Docker.

Implement Spring Boot Application

We will implement simple REST application it is as same as in Building a simple REST Service with Spring Boot. First of all, we need to create a Maven or Gradle project. In this example, we used the Maven as a build tool.

  1. Create a project that name is spring-boot-docker.
  2. Group ID will be com.mydevgeek.
  3. Artifact ID will be spring-boot-docker.
  4. Add the spring-boot-starter-web-1.5.2.RELEASE and the spring-boot-maven-plugin into the pom.xml.
  5. Finally, add Application.java and HomeController.java.

Test in Local Environment

Use this maven command to build and run the application.

mvn package && java -jar target/spring-boot-docker-1.0.jar

Then send a GET request to test the REST service.

http://localhost:8080/

output: – 

Hello World!

Now it’s running perfectly in the local environment.

Create a Docker Image

Create a Dockerfile inside the project without any extension.

spring-boot-and-docker-project-structure

FROM – image name.

VOLUME – Command for mount a directory.

EXPOSE – Set a specific port to listen by Docker Container.

ADD –  uses for copy files.

ENTRYPOINT –  allows you to configure a container that will run as an executable.

Build a Docker Image

Build the Docker image using following commands including the dot.

docker build -f Dockerfile -t spring-boot-docker .

-t – for tagging the image. (in this example tag is spring-boot-docker).

-f – point to a Docker file location.

Using docker images command check all Docker images.

docker-images

Run Docker Image

Use this command to run the Spring Boot application.

docker run -p 8080:8080 spring-boot-docker

run-spring-boot-on-docker-image

 

Finally, test the REST api using the http://localhost:8080/.


Related Post

18688total visits,13visits today

RSS
Follow by Email
Facebook
Facebook
Google+
http://mydevgeek.com/spring-boot-docker
Twitter