Running Java Microservices in Docker

Today, I managed to run my microservices in docker environment successfully.

Table of Contents

Build the microservices

I have written four microservices using Spring Boot. One is Eureka Server and the other three are Eureka Clients.

Docker Tag Name Description Port Source Code Path
ms-server-eureka Spring Boot Application acting as Eureka Discovery Server. 8001 $MS_SRC_BASE/ms.server.eureka/
ms-client-user Spring Boot Client Application connecting to MongoDB. 8002 $MS_SRC_BASE/ms.client.user/
ms-client-product Spring Boot Client Application connecting to MongoDB. 8003 $MS_SRC_BASE/ms.client.product/
ms-client-cart Spring Boot Client Application connecting to MongoDB. 8004 $MS_SRC_BASE/ms.client.cart/
ms-mongodb MongoDB 27017 NIL

Firstly, create Dockerfile for each of the microservice.

Here below is the example for the User Microservice.

FROM openjdk:17-ea-22
COPY target/ms.client.user-0.0.1-SNAPSHOT.jar ms.client.user-SNAPSHOT.jar
EXPOSE 8001
ENTRYPOINT ["java","-jar","/ms.client.user-SNAPSHOT.jar"]

Enter fullscreen mode Exit fullscreen mode

Secondly, build each of the Spring Boot Applications and package to JAR files.

./mvnw -Dmaven.test.skip=true clean package

Enter fullscreen mode Exit fullscreen mode

Thirdly, build docker image of each of the Spring Boot Applications.
*Make sure Docker Engine is running on your development host.

cd $MS_SRC_BASE/ms.server.eureka/
docker build --tag=ms-server-eureka:latest .
cd $MS_SRC_BASE/ms.client.user/
docker build --tag=ms-client-user:latest .
cd $MS_SRC_BASE/ms.client.product/
docker build --tag=ms-client-product:latest .
cd $MS_SRC_BASE/ms.client.cart/
docker build --tag=ms-client-cart:latest .

Enter fullscreen mode Exit fullscreen mode

Deployment

  • In order that the containers can find each other, use --network container:[containerName] to bind to a master container. In this case, I use ms-server-eureka as the master container.
  • All ports are exposed by publishing the ports on the master container.
docker run --name ms-server-eureka -p 8000-8003:8000-8003 -p 27017:27017 ms-server-eureka:latest
docker run --name ms-mongodb --network container:ms-server-eureka -d mongo
docker run --name ms-client-user --network container:ms-server-eureka ms-client-user:latest
docker run --name ms-client-product --network container:ms-server-eureka ms-client-product:latest
docker run --name ms-client-cart --network container:ms-server-eureka ms-client-cart:latest

Enter fullscreen mode Exit fullscreen mode

Verification

  • Check the Eureka Server status by opening http://localhost:8000/ in a web browser.

  • Get data from the User Microservice by opening http://localhost:8001/user/search/findByLastName?name=Administrator in a web browser.

原文链接:Running Java Microservices in Docker

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容