<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vutlhari Ndlovhu on Medium]]></title>
        <description><![CDATA[Stories by Vutlhari Ndlovhu on Medium]]></description>
        <link>https://medium.com/@vhutie?source=rss-91d2cf71f21c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GKyAeUrEW1snxp4yae64Zw@2x.jpeg</url>
            <title>Stories by Vutlhari Ndlovhu on Medium</title>
            <link>https://medium.com/@vhutie?source=rss-91d2cf71f21c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 16:36:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vhutie/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Scale-Up and Load-Balance a Spring-Boot MicroService With Docker-Compose, Persist Data and Enable…]]></title>
            <link>https://medium.com/swlh/scale-up-and-load-balance-a-spring-boot-microservice-with-docker-compose-persist-data-and-enable-4656d2e0775c?source=rss-91d2cf71f21c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4656d2e0775c</guid>
            <category><![CDATA[zuul]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[eureka]]></category>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Vutlhari Ndlovhu]]></dc:creator>
            <pubDate>Sat, 28 Nov 2020 13:58:21 GMT</pubDate>
            <atom:updated>2020-11-28T13:58:21.823Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scale-Up and Load-Balance a Spring-Boot MicroService With Docker-Compose, Persist Data and Enable Netflix Tools Like EUREKA and ZUUL API Gateway (PART 2)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*fbc37AUgcL9U9BiQX4CDiw.png" /></figure><h3>Introduction</h3><p>Finally the second part of an amazing article where we put all the puzzles together. We are going to make sure by the end of this article, all you see in the image above is running locally on your computer. We will start by changing the property file of Customer service to utilize the Postgresql database. Then customize logs and where to be stored. Then containerize ZUUL, EUREKA, and Customer service. Then run them in a docker-compose network. And finally, scale up the Customer service container instance.</p><h3>Prerequisite</h3><p>Please go through part 1(link below) of this article to fully understand.</p><p><a href="https://medium.com/swlh/scale-up-and-load-balance-a-spring-boot-microservice-with-docker-compose-persist-data-and-enable-c004552dcb31">Scale-Up and Load-Balance a Spring-Boot MicroService With Docker-Compose, Persist Data and Enable…</a></p><h3>Customer Service Changing from H2 database to Postgresql Database</h3><p>The first step, clone the Customer Service from Github with the url below</p><pre>git clone <a href="https://github.com/vhutie/superdev-crm-customer.git">https://github.com/vhutie/superdev-crm-customer.git</a></pre><p>Also, clone Eureka</p><pre>git clone <a href="https://github.com/vhutie/superdev-eureka-server.git">https://github.com/vhutie/superdev-eureka-server.git</a></pre><p>And finally, clone ZUUL</p><pre>git clone <a href="https://github.com/vhutie/superdev-zuul.git">https://github.com/vhutie/superdev-zuul.git</a></pre><p>Then change the application.properties file of Customer Service to look exactly as below to accommodate the Postgresql connection settings.</p><pre># Data Source Properties</pre><pre>spring.jpa.database=POSTGRESQL</pre><pre>spring.datasource.platform=postgres</pre><pre>spring.datasource.url=jdbc:postgresql://localhost:5432/superdevdb</pre><pre>spring.datasource.username=superdevuser</pre><pre>spring.datasource.password=P@ssword1</pre><pre>spring.jpa.show-sql=true</pre><pre>spring.jpa.generate-ddl=true</pre><pre>spring.jpa.hibernate.ddl-auto=create-drop</pre><pre>spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true</pre><pre># JPA Properties</pre><pre>spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false</pre><pre>spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl</pre><pre>spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy</pre><pre>#EDIT TO COMPUTER IP ADDRESS</pre><pre>eureka.client.serviceUrl.defaultZone=${EUREKA_SERVER:http://localhost:8761/eureka}</pre><pre>spring.application.name=superdev-crm-customer</pre><p>Then on the pom.xml file, we need to replace the H2 database dependency with Postgresql dependency.</p><pre>&lt;!-- Add postgres dependency for db connection --&gt;</pre><pre>&lt;dependency&gt;</pre><pre>&lt;groupId&gt;org.postgresql&lt;/groupId&gt;</pre><pre>&lt;artifactId&gt;postgresql&lt;/artifactId&gt;</pre><pre>&lt;/dependency&gt;</pre><p>Then to test, we need to start up the database image we created in the article below</p><p><a href="https://vhutie.medium.com/custom-postgres-docker-image-with-predefined-database-and-tables-with-permanent-storage-2c3b44f92aad">Custom Postgres Docker Image with predefined Database and Tables with permanent storage</a></p><p>Then start up Eureka Service, followed by the Customer Service, and finish off by starting up the ZUUL Service. After all, services are up and running, then do a post customer and get customer via Postman. All the steps are included in Part 1 of this article.</p><p>Once you have done the testing, you can stop all running instances of all three services.</p><h3>Containerize all MicroServices</h3><p>In this section, we will containerize all our microservices and make sure they run as separate docker container instances.</p><p>The first step is to add a Dockerfile on each microservice. Create a Dockerfile on the same level as pom.xml on the parent folder of each project and add the same contents as below on each.</p><pre>FROM openjdk:8-jdk-alpine</pre><pre>VOLUME /tmp</pre><pre>ADD target/*.jar app.jar</pre><pre>ENV JAVA_OPTS &quot;-Xmx192m -Xms192m -Djava.security.egd=file:///dev/./urandom -XX:+HeapDumpOnOutOfMemoryError &quot;</pre><pre>ENV TZ Africa/Johannesburg</pre><pre># NOT USE YET -XX:+UseG1GC</pre><pre>ENTRYPOINT [ &quot;sh&quot;, &quot;-c&quot;, &quot;java $JAVA_OPTS -jar /app.jar&quot; ]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*3Sm2V9Cm0MTypjjkbexQhQ.png" /><figcaption>Dockerfile included</figcaption></figure><p>The Dockerfile will be used as instructions when we build each microservice’s image via maven. The instructions in the Dockerfile are simple, we will be building our images based on the openjdk image and once the container is up we will run the jar we included when building the image.</p><p>The second step is to change the pom.xml file and enable maven to assist in building the image on each project. On each project(Customer, Eureka and ZUUL) replace the &lt;build&gt; tags with the below</p><pre>&lt;build&gt;</pre><pre>&lt;plugins&gt;</pre><pre>&lt;plugin&gt;</pre><pre>&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</pre><pre>&lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;</pre><pre>&lt;/plugin&gt;</pre><pre>&lt;plugin&gt;</pre><pre>&lt;groupId&gt;com.spotify&lt;/groupId&gt;</pre><pre>&lt;artifactId&gt;dockerfile-maven-plugin&lt;/artifactId&gt;</pre><pre>&lt;version&gt;1.4.9&lt;/version&gt;</pre><pre>&lt;executions&gt;</pre><pre>&lt;execution&gt;</pre><pre>&lt;id&gt;default&lt;/id&gt;</pre><pre>&lt;goals&gt;</pre><pre>&lt;goal&gt;build&lt;/goal&gt;</pre><pre>&lt;goal&gt;push&lt;/goal&gt;</pre><pre>&lt;/goals&gt;</pre><pre>&lt;/execution&gt;</pre><pre>&lt;/executions&gt;</pre><pre>&lt;configuration&gt;</pre><pre>&lt;repository&gt;superdev/${project.artifactId}&lt;/repository&gt;</pre><pre>&lt;tag&gt;latest&lt;/tag&gt;</pre><pre>&lt;buildArgs&gt;</pre><pre>&lt;JAR_FILE&gt;${project.build.finalName}.jar&lt;/JAR_FILE&gt;</pre><pre>&lt;/buildArgs&gt;</pre><pre>&lt;/configuration&gt;</pre><pre>&lt;/plugin&gt;</pre><pre>&lt;/plugins&gt;</pre><pre>&lt;/build&gt;</pre><p>Then the last step, we need to change the application.properties files of Customer and ZUUL to replace localhost with your computer’s IP address. Reason being when they run as microservices, they will not be able to access the other microservices, Eureka, or database as localhost but Global IP address. When we get to the docker-compose section we will change this again to a hostname instead.</p><p>Customer application.properties to look as below(DONT FORGET TO EDIT IP ADDRESS)</p><pre># Data Source Properties</pre><pre>spring.jpa.database=POSTGRESQL</pre><pre>spring.datasource.platform=postgres</pre><pre>#EDIT TO COMPUTER IP ADDRESS</pre><pre>spring.datasource.url=jdbc:postgresql://192.XXX.XXX.1:5432/superdevdb</pre><pre>spring.datasource.username=superdevuser</pre><pre>spring.datasource.password=P@ssword1</pre><pre>spring.jpa.show-sql=true</pre><pre>spring.jpa.generate-ddl=true</pre><pre>spring.jpa.hibernate.ddl-auto=create-drop</pre><pre>spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true</pre><pre># JPA Properties</pre><pre>spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false</pre><pre>spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl</pre><pre>spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy</pre><pre>#EDIT TO COMPUTER IP ADDRESS</pre><pre>eureka.client.serviceUrl.defaultZone=${EUREKA_SERVER:http://192.XXX.XXX.1:8761/eureka}</pre><pre>spring.application.name=superdev-crm-customer</pre><p>And ZUUL’s application.properties to look as below. (DONT FORGET TO EDIT IP ADDRESS)</p><pre>server.port=8081</pre><pre>#EDIT TO COMPUTER IP ADDRESS</pre><pre>eureka.client.serviceUrl.defaultZone=${EUREKA_SERVER:http://192.XXX.XXX.1:8761/eureka}</pre><pre>spring.application.name=superdev-zuul</pre><pre>#EDIT TO COMPUTER IP ADDRESS</pre><pre>zuul.routes.customer.url=http://192.XXX.XXX.1:8080</pre><pre>ribbon.eureka.enabled=false</pre><h3>Building the Microservices’ docker images</h3><p><strong>For ZUUL</strong>- Go to your terminal/command prompt and navigate to the parent folder of the ZUUL project, make sure the folder has the pom.xml file, or else the following command won’t work. Provided you have installed maven on your computer run the below command</p><pre>mvn clean install</pre><p>You should see the results below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*MBSgq3EpcjcwzXLHop7zJg.png" /></figure><p>Then run docker images command and should see superdev/superdev-zuul:latest as part of the image list</p><pre>docker images</pre><p><strong>For EUREKA</strong>- Go to your terminal/command prompt and navigate to the parent folder of the EUREKA project, make sure the folder has the pom.xml file, or else the following command won’t work. Provided you have installed maven on your computer run the below command</p><pre>mvn clean install</pre><p>You should see the results below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b2vOuzJCQq5OZkR1dxWP0Q.png" /></figure><p>Then run docker images command and should see superdev/superdev-eureka-server:latest as part of the image list</p><pre>docker images</pre><p><strong>For Customer Service</strong>- Go to your terminal/command prompt and navigate to the parent folder of the Customer project, make sure the folder has the pom.xml file, or else the following command won’t work. Provided you have installed maven on your computer run the below command</p><pre>mvn clean install</pre><p>You should see the results below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OPti3cYwMbihggH_Fez9zw.png" /></figure><p>Then run docker images command and should see superdev/superdev-crm-customer:latest as part of the image list</p><pre>docker images</pre><h3>Running the Microservice Docker Images</h3><p>We will start by silently running the Eureka Image as below and port forward 8761</p><pre>docker run -d --rm -p 8761:8761 superdev/superdev-eureka-server:latest &amp;</pre><p>Then followed by Customer Service Image as below and port forward 8080</p><pre>docker run -d --rm -p 8080:8080 superdev/superdev-crm-customer:latest &amp;</pre><p>Then finally silently run ZUUL image and port forward 8081</p><pre>docker run -d --rm -p 8081:8081 superdev/superdev-zuul:latest &amp;</pre><p>Check if all 4(including database) images are up and running</p><pre>docker ps -a</pre><p>And you should get results similar to the below image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pXwHgNAd2F6dn2EfcLzsrw.png" /></figure><p>After all container instances are up and running, then do a post customer and get customer via Postman. All the steps are included in Part 1 of this article.</p><h3>Running images via docker-compose and scaling up</h3><p><strong>Step 1 — Install docker-compose following the steps on the link below</strong></p><p><a href="https://docs.docker.com/compose/install/"></a></p><p><strong>Step 2 — Move logs to a permenart docker mounted directory</strong></p><p>To enable logging outside of your docker container, add logback.xml file in your resources folder on each project and rebuild all your microservice images followiling the same instructions we used when building the images the first time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*-4cCPjDOUnIKoVM368a6qA.png" /><figcaption>logback.xml file</figcaption></figure><p>Make sure your file has your preferred logging settings like below</p><pre>&lt;?xml version=<em>&quot;1.0&quot;</em> encoding=<em>&quot;UTF-8&quot;</em>?&gt;</pre><pre>&lt;configuration&gt;</pre><pre>&lt;property name=<em>&quot;LOG_PATH&quot;</em> value=<em>&quot;logs&quot;</em>/&gt;</pre><pre>&lt;property name=<em>&quot;APP_NAME&quot;</em> value=<em>&quot;superdev-crm-customer&quot;</em>/&gt;</pre><pre>&lt;timestamp key=<em>&quot;currentTimestamp&quot;</em> datePattern=<em>&quot;yyyy-MM-dd&#39;_&#39;HH&quot;</em>/&gt;</pre><pre>&lt;appender name=<em>&quot;STDOUT&quot;</em> class=<em>&quot;ch.qos.logback.core.ConsoleAppender&quot;</em>&gt;</pre><pre>&lt;encoder&gt;</pre><pre>&lt;pattern&gt;</pre><pre>%d{dd-MM-yyyy HH:mm:ss.SSS} %magenta([%thread]) %highlight(%-5level) %logger.%M\(%line\) - %msg%n</pre><pre>&lt;/pattern&gt;</pre><pre>&lt;/encoder&gt;</pre><pre>&lt;/appender&gt;</pre><pre>&lt;appender name=<em>&quot;SAVE-TO-FILE&quot;</em></pre><pre>class=<em>&quot;ch.qos.logback.core.rolling.RollingFileAppender&quot;</em>&gt;</pre><pre>&lt;file&gt;${LOG_PATH}/${APP_NAME}.log&lt;/file&gt;</pre><pre>&lt;encoder class=<em>&quot;ch.qos.logback.classic.encoder.PatternLayoutEncoder&quot;</em>&gt;</pre><pre>&lt;Pattern&gt;</pre><pre>%d{dd-MM-yyyy HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M - %msg%n</pre><pre>&lt;/Pattern&gt;</pre><pre>&lt;/encoder&gt;</pre><pre>&lt;rollingPolicy class=<em>&quot;ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy&quot;</em>&gt;</pre><pre>&lt;maxFileSize&gt;100MB&lt;/maxFileSize&gt;</pre><pre>&lt;fileNamePattern&gt;</pre><pre>${LOG_PATH}/archived/${APP_NAME}.%d{yyyy-MM-dd}.%i.log</pre><pre>&lt;/fileNamePattern&gt;</pre><pre>&lt;maxHistory&gt;30&lt;/maxHistory&gt;</pre><pre>&lt;totalSizeCap&gt;1GB&lt;/totalSizeCap&gt;</pre><pre>&lt;/rollingPolicy&gt;</pre><pre>&lt;/appender&gt;</pre><pre>&lt;root level=<em>&quot;INFO&quot;</em>&gt;</pre><pre>&lt;appender-ref ref=<em>&quot;STDOUT&quot;</em>/&gt;</pre><pre>&lt;appender-ref ref=<em>&quot;SAVE-TO-FILE&quot;</em>/&gt;</pre><pre>&lt;/root&gt;</pre><pre>&lt;/configuration&gt;</pre><p>After rebuilding, your logs will be stored in /logs/superdev-crm-customer.log</p><p>Repeat the above for the other projects and rename the APP-NAME</p><p><strong>Step 3— Create a docker-compose file with all the images we created</strong></p><p>Create a folder in the path of your choice</p><pre>mkdir /opt/workspace/nerdcode/docker/docker-compose/sudper-devs</pre><p>Navigate to the directory and create a docker-compose file</p><pre>cd /opt/workspace/nerdcode/docker/docker-compose/sudper-devs<br>touch docker-compose.yml</pre><p>Open the file with an editor of your choice and paste the below content</p><pre>version: &#39;2.2&#39;<br>services:</pre><pre>superdev-postgres: #name of the first service<br>    image: medium/database:latest<br>    container_name: postgres_superdev<br>    restart: always<br>    volumes:<br>      - /opt/workspace/nerdcode/docker/data/medium:/var/lib/postgresql/data:rw<br>    environment:<br>     - POSTGRES_PASSWORD=P@ssword1<br>    ports:<br>      - &quot;5432:5432&quot; #specify ports forewarding<br>    mem_limit: 1g<br>    mem_reservation: 512m<br>    cpus: 1.5<br>    networks:<br>      microservice_network:<br>        aliases:<br>          - postgres-server</pre><pre>superdev-eureka:<br>    image: &#39;superdev/superdev-eureka-server:latest&#39;<br>    restart: always<br>    volumes:<br>      - /opt/workspace/nerdcode/docker/data/logs:/logs:rw<br>    ports:<br>      # both ports must match the port from external_url above<br>      - &quot;8761:8761&quot;<br>    mem_limit: 512m<br>    mem_reservation: 256m<br>    cpus: 1<br>    networks:<br>      microservice_network:<br>        aliases:<br>          - eureka-server</pre><pre>superdev-crm-customer:<br>    image: &#39;superdev/superdev-crm-customer:latest&#39;<br>    restart: always<br>    volumes:<br>      - /opt/workspace/nerdcode/docker/data/logs:/logs:rw<br>    mem_limit: 256m<br>    mem_reservation: 128m<br>    cpus: 0.5<br>    depends_on:<br>      - &quot;superdev-eureka&quot;<br>    networks:<br>      microservice_network:</pre><pre>superdev-zuul:<br>    image: &#39;superdev/superdev-zuul:latest&#39;<br>    restart: always<br>    volumes:<br>      - /opt/workspace/nerdcode/docker/data/logs:/logs:rw<br>    ports:<br>      # both ports must match the port from external_url above<br>      - &quot;8081:8081&quot;<br>    mem_limit: 256m<br>    mem_reservation: 128m<br>    cpus: 0.5<br>    depends_on:<br>      - &quot;superdev-eureka&quot;<br>      - &quot;superdev-crm-customer&quot;<br>    networks:<br>      microservice_network:</pre><pre>networks:<br>  microservice_network:<br>    ipam:<br>      driver: default</pre><p>The docker file above has all the setting we need for our different images, We mounted the database volume and also mounted our microservice logs directory.</p><p><strong>Step 4 — Check if the docker-compose file has no errors</strong></p><p>Run the following command in the directory wchich contains your docker-compose file</p><pre>docker-compose config</pre><p>If you have errors, it will indicate but if all is well it will print the contents of your docker-compose file.</p><p><strong>Step 5 — Run docker-compose</strong></p><p>Run the following command in the directory wchich contains your docker-compose file</p><pre>docker-compose up &amp;</pre><p>If all is well, all your images should be up and running.</p><p><strong>Step 6— Stop docker-compose</strong></p><p>Run the following command in the directory wchich contains your docker-compose file</p><pre>docker-compose down</pre><p>Now all your containers should have stopped running</p><p><strong>Step 7 — Lets change how the images see each other</strong></p><p>We once had them seeing each other via your computer’s IP address, now since we have a docker-compose network enabled, we will use their network hostname.</p><p>We need to change how we reference Eureka, Customer Service and database.</p><p>On the application.property of each project referencing Eureka, change IP address to Eureka hostname like below</p><p>For Customer Service’s application.properties</p><pre># Data Source Properties</pre><pre>spring.jpa.database=POSTGRESQL</pre><pre>spring.datasource.platform=postgres</pre><pre>#EDIT TO DATABASE HOSTNAME</pre><pre>spring.datasource.url=jdbc:postgresql://postgres-server:5432/superdevdb</pre><pre>spring.datasource.username=superdevuser</pre><pre>spring.datasource.password=P@ssword1</pre><pre>spring.jpa.show-sql=true</pre><pre>spring.jpa.generate-ddl=true</pre><pre>#WE EDIT THE BELOW TO KEEP DATA PERMANENTLY</pre><pre>spring.jpa.hibernate.ddl-auto=update</pre><pre>spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true</pre><pre># JPA Properties</pre><pre>spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false</pre><pre>spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl</pre><pre>spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy</pre><pre>#EDIT TO HOSTNAME </pre><pre>eureka.client.serviceUrl.defaultZone=${EUREKA_SERVER:http://eureka-server:8761/eureka}</pre><pre>spring.application.name=superdev-crm-customer</pre><p>And change ZUUL’s application.properties</p><pre>server.port=8081</pre><pre>#EDIT TO DOCKER_COMPOSE HOSTNAME</pre><pre>eureka.client.serviceUrl.defaultZone=${EUREKA_SERVER:http://eureka-server:8761/eureka}</pre><pre>spring.application.name=superdev-zuul</pre><pre>#CHANGED FROM URL</pre><pre>#zuul.routes.customer.url=http://superdev-crm-customer:8080</pre><pre>#NOW USING SERVICE ID</pre><pre>zuul.routes.customer.serviceId=superdev-crm-customer</pre><pre>eureka.client.registerWithEureka=true</pre><pre>eureka.client.fetchRegistry=true</pre><pre>#TO AVAID TIMEOUT ERRORS PLEASE ADD THE 2 LINES BELOW</pre><pre>zuul.host.socket-timeout-millis=60000</pre><pre>ribbon.ReadTimeout=60000</pre><p>Rebuild images and run docker-compose</p><p><strong>Step 8 — Scaling up and down</strong></p><p>Finally we get to this exciting part, scaling up and down.</p><p>If you look at our docker-compose file closely, you will realize that Customer service doesn’t expose any ports externally, which leaves us with one entry point which is our ZUUL API gateway. This also means we can scale up the microservice od Customer since there won’t be any external port clushes.</p><p>To scale up 4 instances of the Customer Service run the below command, you can play around with the number</p><pre>docker-compose up --scale superdev-crm-customer=4</pre><p>There are many ways to verify if your instances are running</p><p>Command you can use to check statistics of docker engine</p><pre>docker stats</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m_uodJJdvCsOds0Tr_6l7g.png" /></figure><p>As you can see from the results above, Customer Service is running with 4 instances</p><p>or docker ps command</p><pre>docker ps -a</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_CKKiSpVEOguKH8Xj4vPhg.png" /></figure><p>or you can check on the Eureka dashboard</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0M1Njd8HbMensM4MTlUCsQ.png" /></figure><p><strong>Resources of PART 2 can be cloned from GitHub</strong></p><pre>git clone <a href="https://github.com/vhutie/superdev-crm-customer-part2.git">https://github.com/vhutie/superdev-crm-customer-part2.git</a><br>git clone <a href="https://github.com/vhutie/superdev-eureka-server-part2.git">https://github.com/vhutie/superdev-eureka-server-part2.git</a><br>git clone <a href="https://github.com/vhutie/superdev-zuul-part2.git">https://github.com/vhutie/superdev-zuul-part2.git</a></pre><h3>Conclusion</h3><p>Part 2 of this article has finally come to an end, you can now test your services if they working and load balanced. Every time you issue a request to ZUUL, it will not call the same instance of your Customer Service twice in a row.</p><p>Now you are all set. Share, like, and teach others… The next article will focus on using this article to have multiple microservices orchestrated using a workflow engine. We honestly cannot wait.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4656d2e0775c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/scale-up-and-load-balance-a-spring-boot-microservice-with-docker-compose-persist-data-and-enable-4656d2e0775c">Scale-Up and Load-Balance a Spring-Boot MicroService With Docker-Compose, Persist Data and Enable…</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scale-Up and Load-Balance a Spring-Boot MicroService With Docker-Compose, Persist Data and Enable…]]></title>
            <link>https://medium.com/swlh/scale-up-and-load-balance-a-spring-boot-microservice-with-docker-compose-persist-data-and-enable-c004552dcb31?source=rss-91d2cf71f21c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c004552dcb31</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[eureka]]></category>
            <category><![CDATA[netflix-zuul]]></category>
            <category><![CDATA[load-balancing]]></category>
            <dc:creator><![CDATA[Vutlhari Ndlovhu]]></dc:creator>
            <pubDate>Fri, 13 Nov 2020 11:53:38 GMT</pubDate>
            <atom:updated>2020-11-14T12:55:14.406Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scale-Up and Load-Balance a Spring-Boot MicroService With Docker-Compose, Persist Data and Enable Netflix Tools Like EUREKA and ZUUL API Gateway (PART 1)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*n8z_b9QNdnL-IyddxNWZ_w.png" /><figcaption>Please look at the overview image of what we are going to accomplish today</figcaption></figure><h3><strong>Introduction</strong></h3><p>An amazing, amazing article this is. The power of having different docker image containers talk to each other in a seamless way is amazing. In this article, that’s exactly what we’ll be doing. We going to access a scaled-up CRUD(create, read, update and delete) REST API microservice via an API gateway and store its data on a PostgreSQL database server. We will have 4 docker images at the end of this article. One for PostgreSQL, one for REST API microservice, one for EUREKA to enable round-robin load-balancing, and the last one for ZUUL API gateway. To easily manage the containers we’ll use docker-compose. The journey to a super full stack developer takes one article at a time.</p><h3>Prerequisite</h3><p>Please read the “Custom Postgres Docker Image with predefined Database and Tables with permanent storage” first to be able to complete this part one and part 2 article. Find the link below</p><p><a href="https://vhutie.medium.com/custom-postgres-docker-image-with-predefined-database-and-tables-with-permanent-storage-2c3b44f92aad">Custom Postgres Docker Image with predefined Database and Tables with permanent storage</a></p><h3><strong>Create 3 projects to start our journey</strong></h3><ol><li><strong>Create EUREKA Server Project</strong></li></ol><p>To <strong>start from scratch</strong>, you need to head over to the below URL:</p><pre><a href="https://start.spring.io/">https://start.spring.io/</a></pre><p>And edit the group and artifact and add the dependencies needed by the project. Also, change the java version to 8. Please look at the image below and make sure you have similar dependencies</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u7GvExZ_kdS_Na_YKHH3QA.png" /></figure><p><strong>Dependencies explained:</strong></p><p><strong>Eureka Server </strong>— Enable our project to be a EUREKA server, which will, in turn, discover all the other projects</p><p><strong>Spring Boot Actuator </strong>— To enable our project to be monitored by the EUREKA server and any other monitoring tools will be able to ping this service’s uptime.</p><p>After generating the project and unzipping it. Edit the Spring Boot Application class: SuperdevEurekaServerApplication</p><pre><strong>package</strong> za.co.superdev.discovery;</pre><pre><strong>import</strong> org.springframework.boot.SpringApplication;</pre><pre><strong>import</strong> org.springframework.boot.autoconfigure.SpringBootApplication;</pre><pre><strong>import</strong> org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;</pre><pre>@SpringBootApplication</pre><pre>@EnableEurekaServer</pre><pre><strong>public</strong> <strong>class</strong> SuperdevEurekaServerApplication {</pre><pre><strong>public</strong> <strong>static</strong> <strong>void</strong> main(String[] args) {</pre><pre>SpringApplication.<em>run</em>(SuperdevEurekaServerApplication.<strong>class</strong>, args);</pre><pre>}</pre><pre>}</pre><p>And the last thing to edit is application.property</p><pre>eureka.client.registerWithEureka = false</pre><pre>eureka.client.fetchRegistry = false</pre><pre>server.port = 8761</pre><pre>spring.application.name=superdev-eureka-server</pre><p>Now you can start the Netflix EUREKA Server and check what is on the dashboard. Go to your terminal/command prompt and navigate to the parent folder of EUREKA project, make sure the folder has the pom.xml file, or else the following command won’t work.</p><pre>mvn clean spring-boot:run</pre><p>Then on your browser type the following URL:</p><pre><a href="http://localhost:8761/">http://localhost:8761/</a></pre><p>You should see the EUREKA Server Dashboard page like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GvRqsxQHwd5oAn8BsAvbuw.png" /></figure><p>We are done with the first project, on to the next one</p><p>You can find the complete code for the EUREKA Server on the below GitHub link</p><pre><a href="https://github.com/vhutie/superdev-eureka-server.git">https://github.com/vhutie/superdev-eureka-server.git</a></pre><p><strong>2. Create a JPA Spring boot project</strong></p><p>To <strong>start from scratch</strong>, you need to head over to the below URL:</p><pre><a href="https://start.spring.io/">https://start.spring.io/</a></pre><p>And edit the group and artifact and add the dependencies needed by the project. Also, change the java version to 8. Please look at the image below and make sure you have similar dependencies</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7MJqoDwQQ8P7o_6TXUIpSg.png" /></figure><p><strong>Dependencies explained:</strong></p><p><strong>Spring Data JPA </strong>— We need it to assist us with the seamless persistence of data from java to any connected DB without doing the traditional connection or session setup and management via annotations.</p><p><strong>Spring Web</strong> — We need it to enable REST API on our project, exposing web services in a seamless way via annotations.</p><p><strong>H2 Database</strong> — Enable our project to communicate with an H2 Database, connecting and managing data in between.</p><p><strong>Eureka Discovery Client </strong>— Enable our project to be discovered by a Eureka server and allow our services to communicate with this service in a seamless way.</p><p><strong>Spring Boot Actuator </strong>— To enable our project to be monitored by EUREKA server and any other monitoring tools will be able to ping this service’s uptime.</p><p>Once all is done, click generate and the project will be automatically downloaded to your download folder. Then move it to your preferred location.</p><p>Then Open the project with your favorite IDE and check if all is in order as in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*IG0u-QbcQafFxSlfdDNu7w.png" /></figure><p>Let’s quickly edit the project to have at least a working rest api jpa enabled project.</p><p>We will need the following classes:</p><p><strong>POJO(Plain Old Java Object) Entity Class</strong> to have data to object mappings via annotations</p><pre><strong>package</strong> za.co.superdev.crm.model;</pre><pre><strong>import</strong> java.util.Date;</pre><pre><strong>import</strong> javax.persistence.Entity;</pre><pre><strong>import</strong> javax.persistence.GeneratedValue;</pre><pre><strong>import</strong> javax.persistence.GenerationType;</pre><pre><strong>import</strong> javax.persistence.Id;</pre><pre>@Entity</pre><pre><strong>public</strong> <strong>class</strong> Customer {</pre><pre>@Id</pre><pre>@GeneratedValue(strategy=GenerationType.<strong><em>AUTO</em></strong>)</pre><pre><strong>private</strong> Long id;</pre><pre><strong>private</strong> String name;</pre><pre><strong>private</strong> String surname;</pre><pre><strong>private</strong> Integer age;</pre><pre><strong>private</strong> Date creationDate;</pre><pre><strong>private</strong> Date lastUpdateDate;</pre><pre><strong>public</strong> Long getId() {</pre><pre><strong>return</strong> id;</pre><pre>}</pre><pre><strong>public</strong> <strong>void</strong> setId(Long id) {</pre><pre><strong>this</strong>.id = id;</pre><pre>}</pre><pre><strong>public</strong> String getName() {</pre><pre><strong>return</strong> name;</pre><pre>}</pre><pre><strong>public</strong> <strong>void</strong> setName(String name) {</pre><pre><strong>this</strong>.name = name;</pre><pre>}</pre><pre><strong>public</strong> String getSurname() {</pre><pre><strong>return</strong> surname;</pre><pre>}</pre><pre><strong>public</strong> <strong>void</strong> setSurname(String surname) {</pre><pre><strong>this</strong>.surname = surname;</pre><pre>}</pre><pre><strong>public</strong> Integer getAge() {</pre><pre><strong>return</strong> age;</pre><pre>}</pre><pre><strong>public</strong> <strong>void</strong> setAge(Integer age) {</pre><pre><strong>this</strong>.age = age;</pre><pre>}</pre><pre><strong>public</strong> Date getCreationDate() {</pre><pre><strong>return</strong> creationDate;</pre><pre>}</pre><pre><strong>public</strong> <strong>void</strong> setCreationDate(Date creationDate) {</pre><pre><strong>this</strong>.creationDate = creationDate;</pre><pre>}</pre><pre><strong>public</strong> Date getLastUpdateDate() {</pre><pre><strong>return</strong> lastUpdateDate;</pre><pre>}</pre><pre><strong>public</strong> <strong>void</strong> setLastUpdateDate(Date lastUpdateDate) {</pre><pre><strong>this</strong>.lastUpdateDate = lastUpdateDate;</pre><pre>}</pre><pre>@Override</pre><pre><strong>public</strong> String toString() {</pre><pre><strong>return</strong> String.<em>format</em>(</pre><pre>&quot;Customer[id=%d, Name=&#39;%s&#39;, Surname=&#39;%s&#39;, Age=&#39;%s&#39;]&quot;,</pre><pre>id, name, surname, age);</pre><pre>}</pre><pre>}</pre><p><strong>JPA Repository Interface</strong> handles the communication between our entity class and database. On this interface, you are able to define JPA queries and Native Queries.</p><pre><strong>package</strong> za.co.superdev.crm.repo;</pre><pre><strong>import</strong> java.util.List;</pre><pre><strong>import</strong> org.springframework.data.repository.CrudRepository;</pre><pre><strong>import</strong> za.co.superdev.crm.model.Customer;</pre><pre><strong>public</strong> <strong>interface</strong> CustomerRepository <strong>extends</strong> CrudRepository&lt;Customer, Long&gt; {</pre><pre>List&lt;Customer&gt; findByName(String name);</pre><pre>Customer findById(<strong>long</strong> id);</pre><pre>}</pre><p><strong>Service Class</strong> is a Service annotated class which we use for any logic of how the database can store, retrieve, update, and delete data.</p><pre><strong>package</strong> za.co.superdev.crm.service;</pre><pre><strong>import</strong> org.springframework.beans.factory.annotation.Autowired;</pre><pre><strong>import</strong> org.springframework.stereotype.Service;</pre><pre><strong>import</strong> za.co.superdev.crm.model.Customer;</pre><pre><strong>import</strong> za.co.superdev.crm.repo.CustomerRepository;</pre><pre><strong>import</strong> java.util.Date;</pre><pre><strong>import</strong> java.util.List;</pre><pre><strong>import</strong> java.util.Objects;</pre><pre><strong>import</strong> java.util.Optional;</pre><pre><strong>import</strong> org.slf4j.Logger;</pre><pre><strong>import</strong> org.slf4j.LoggerFactory;</pre><pre>@Service</pre><pre><strong>public</strong> <strong>class</strong> CustomerService {</pre><pre><strong>private</strong> <strong>static</strong> <strong>final</strong> Logger <strong><em>logger</em></strong> = LoggerFactory.<em>getLogger</em>(CustomerService.<strong>class</strong>);</pre><pre>@Autowired</pre><pre><strong>private</strong> CustomerRepository customerRepository;</pre><pre><strong>public</strong> Customer create(Customer customer) <strong>throws</strong> Exception</pre><pre>{</pre><pre><strong>try</strong></pre><pre>{</pre><pre>customer.setCreationDate(<strong>new</strong> Date());</pre><pre>Customer customerSaved = customerRepository.save(customer);</pre><pre><strong>return</strong> customerSaved;</pre><pre>} <strong>catch</strong>(Exception e ) {</pre><pre><strong><em>logger</em></strong>.error(&quot;Exception occured Cause {} Message {} exception {}&quot;,e.getCause(), e.getMessage(), e);</pre><pre><strong>throw</strong> <strong>new</strong> Exception(&quot;The resource you were trying to reach is not found&quot;);</pre><pre>}</pre><pre>}</pre><pre><strong>public</strong> Customer findById(Long customerId) <strong>throws</strong> Exception</pre><pre>{</pre><pre><strong>try</strong></pre><pre>{</pre><pre>Optional&lt;Customer&gt; customerOptional = customerRepository.findById(customerId);</pre><pre><strong>if</strong>(customerOptional.isPresent())</pre><pre><strong>return</strong> customerOptional.get();</pre><pre><strong>else</strong></pre><pre><strong>throw</strong> <strong>new</strong> Exception(&quot;The resource you were trying to reach is not found&quot;);</pre><pre>} <strong>catch</strong>(Exception e ) {</pre><pre><strong><em>logger</em></strong>.error(&quot;Exception occured Cause {} Message {} exception {}&quot;,e.getCause(), e.getMessage(), e);</pre><pre><strong>throw</strong> <strong>new</strong> Exception(&quot;The resource you were trying to reach is not found&quot;);</pre><pre>}</pre><pre>}</pre><pre><strong>public</strong> List&lt;Customer&gt; findByName(String customerName) <strong>throws</strong> Exception</pre><pre>{</pre><pre><strong>try</strong></pre><pre>{</pre><pre>List&lt;Customer&gt; customerList = customerRepository.findByName(customerName);</pre><pre><strong>if</strong>(!Objects.<em>isNull</em>(customerList))</pre><pre><strong>return</strong> customerList;</pre><pre><strong>else</strong></pre><pre><strong>throw</strong> <strong>new</strong> Exception(&quot;The resource you were trying to reach is not found&quot;);</pre><pre>} <strong>catch</strong>(Exception e ) {</pre><pre><strong><em>logger</em></strong>.error(&quot;Exception occured Cause {} Message {} exception {}&quot;,e.getCause(), e.getMessage(), e);</pre><pre><strong>throw</strong> <strong>new</strong> Exception(&quot;The resource you were trying to reach is not found&quot;);</pre><pre>}</pre><pre>}</pre><pre><strong>public</strong> List&lt;Customer&gt; findAll() <strong>throws</strong> Exception</pre><pre>{</pre><pre><strong>try</strong></pre><pre>{</pre><pre>List&lt;Customer&gt; customerList = customerRepository.findAll();</pre><pre><strong>if</strong>(!Objects.<em>isNull</em>(customerList))</pre><pre><strong>return</strong> customerList;</pre><pre><strong>else</strong></pre><pre><strong>throw</strong> <strong>new</strong> Exception(&quot;The resource you were trying to reach is not found&quot;);</pre><pre>} <strong>catch</strong>(Exception e ) {</pre><pre><strong><em>logger</em></strong>.error(&quot;Exception occured Cause {} Message {} exception {}&quot;,e.getCause(), e.getMessage(), e);</pre><pre><strong>throw</strong> <strong>new</strong> Exception(&quot;The resource you were trying to reach is not found&quot;);</pre><pre>}</pre><pre>}</pre><pre>}</pre><p><strong>Controller class,</strong> with this class we can expose our JPA project to a REST API web service</p><pre><strong>package</strong> za.co.superdev.crm.controller;</pre><pre><strong>import</strong> java.util.List;</pre><pre><strong>import</strong> org.slf4j.Logger;</pre><pre><strong>import</strong> org.slf4j.LoggerFactory;</pre><pre><strong>import</strong> org.springframework.beans.factory.annotation.Autowired;</pre><pre><strong>import</strong> org.springframework.http.HttpStatus;</pre><pre><strong>import</strong> org.springframework.http.ResponseEntity;</pre><pre><strong>import</strong> org.springframework.web.bind.annotation.CrossOrigin;</pre><pre><strong>import</strong> org.springframework.web.bind.annotation.GetMapping;</pre><pre><strong>import</strong> org.springframework.web.bind.annotation.PathVariable;</pre><pre><strong>import</strong> org.springframework.web.bind.annotation.PostMapping;</pre><pre><strong>import</strong> org.springframework.web.bind.annotation.RequestBody;</pre><pre><strong>import</strong> org.springframework.web.bind.annotation.RequestMapping;</pre><pre><strong>import</strong> org.springframework.web.bind.annotation.ResponseBody;</pre><pre><strong>import</strong> org.springframework.web.bind.annotation.RestController;</pre><pre><strong>import</strong> za.co.superdev.crm.model.Customer;</pre><pre><strong>import</strong> za.co.superdev.crm.service.CustomerService;</pre><pre>@RestController</pre><pre>@RequestMapping(&quot;v1/api/customer&quot;)</pre><pre><strong>public</strong> <strong>class</strong> CustomerController {</pre><pre><strong>private</strong> <strong>static</strong> <strong>final</strong> Logger <strong><em>LOGGER</em></strong> = LoggerFactory.<em>getLogger</em>(CustomerController.<strong>class</strong>);</pre><pre>@Autowired</pre><pre><strong>private</strong> CustomerService customerService;</pre><pre>@CrossOrigin(origins = &quot;*&quot;)</pre><pre>@PostMapping</pre><pre><strong>public</strong> @ResponseBody ResponseEntity&lt;Object&gt; createUser(@RequestBody Customer customer) {</pre><pre><strong>try</strong> {</pre><pre>Customer response = customerService.create(customer);</pre><pre><strong>return</strong> <strong>new</strong> ResponseEntity&lt;&gt;(response, HttpStatus.<strong><em>OK</em></strong>);</pre><pre>}<strong>catch</strong> (Exception e) {</pre><pre><strong>for</strong> (StackTraceElement ste : e.getStackTrace()) {</pre><pre><strong><em>LOGGER</em></strong>.error(ste.toString());</pre><pre>}</pre><pre><strong><em>LOGGER</em></strong>.error(e.getMessage());</pre><pre><strong>return</strong> <strong>new</strong> ResponseEntity&lt;&gt;(e.getMessage(), HttpStatus.<strong><em>INTERNAL_SERVER_ERROR</em></strong>);</pre><pre>}</pre><pre>}</pre><pre>@CrossOrigin(origins = &quot;*&quot;)</pre><pre>@GetMapping(&quot;/{customerId}&quot;)</pre><pre><strong>public</strong> @ResponseBody ResponseEntity&lt;Object&gt; getById(@PathVariable(name = &quot;customerId&quot;, required = <strong>true</strong>) Long customerId) {</pre><pre><strong>try</strong> {</pre><pre>Customer response = customerService.findById(customerId);</pre><pre><strong>return</strong> <strong>new</strong> ResponseEntity&lt;&gt;(response, HttpStatus.<strong><em>OK</em></strong>);</pre><pre>}<strong>catch</strong> (Exception e) {</pre><pre><strong>for</strong> (StackTraceElement ste : e.getStackTrace()) {</pre><pre><strong><em>LOGGER</em></strong>.error(ste.toString());</pre><pre>}</pre><pre><strong><em>LOGGER</em></strong>.error(e.getMessage());</pre><pre><strong>return</strong> <strong>new</strong> ResponseEntity&lt;&gt;(e.getMessage(), HttpStatus.<strong><em>INTERNAL_SERVER_ERROR</em></strong>);</pre><pre>}</pre><pre>}</pre><pre>@CrossOrigin(origins = &quot;*&quot;)</pre><pre>@GetMapping(&quot;/extended/{customerName}&quot;)</pre><pre><strong>public</strong> @ResponseBody ResponseEntity&lt;Object&gt; getByName(@PathVariable(name = &quot;customerName&quot;, required = <strong>true</strong>) String customerName) {</pre><pre><strong>try</strong> {</pre><pre>List&lt;Customer&gt; response = customerService.findByName(customerName);</pre><pre><strong>return</strong> <strong>new</strong> ResponseEntity&lt;&gt;(response, HttpStatus.<strong><em>OK</em></strong>);</pre><pre>}<strong>catch</strong> (Exception e) {</pre><pre><strong>for</strong> (StackTraceElement ste : e.getStackTrace()) {</pre><pre><strong><em>LOGGER</em></strong>.error(ste.toString());</pre><pre>}</pre><pre><strong><em>LOGGER</em></strong>.error(e.getMessage());</pre><pre><strong>return</strong> <strong>new</strong> ResponseEntity&lt;&gt;(e.getMessage(), HttpStatus.<strong><em>INTERNAL_SERVER_ERROR</em></strong>);</pre><pre>}</pre><pre>}</pre><pre>@CrossOrigin(origins = &quot;*&quot;)</pre><pre>@GetMapping</pre><pre><strong>public</strong> @ResponseBody ResponseEntity&lt;Object&gt; getAll() {</pre><pre><strong>try</strong> {</pre><pre>List&lt;Customer&gt; response = customerService.findAll();</pre><pre><strong>return</strong> <strong>new</strong> ResponseEntity&lt;&gt;(response, HttpStatus.<strong><em>OK</em></strong>);</pre><pre>}<strong>catch</strong> (Exception e) {</pre><pre><strong>for</strong> (StackTraceElement ste : e.getStackTrace()) {</pre><pre><strong><em>LOGGER</em></strong>.error(ste.toString());</pre><pre>}</pre><pre><strong><em>LOGGER</em></strong>.error(e.getMessage());</pre><pre><strong>return</strong> <strong>new</strong> ResponseEntity&lt;&gt;(e.getMessage(), HttpStatus.<strong><em>INTERNAL_SERVER_ERROR</em></strong>);</pre><pre>}</pre><pre>}</pre><pre>}</pre><p>Edit application.properties</p><pre>spring.datasource.url=jdbc:h2:mem:testdb</pre><pre>spring.datasource.driverClassName=org.h2.Driver</pre><pre>spring.datasource.username=sa</pre><pre>spring.datasource.password=password</pre><pre>spring.jpa.database-platform=org.hibernate.dialect.H2Dialect</pre><pre>#EDIT TO COMPUTER IP ADDRESS</pre><pre>eureka.client.serviceUrl.defaultZone=${EUREKA_SERVER:http://localhost:8761/eureka}</pre><pre>spring.application.name=superdev-crm-customer</pre><p>Your project structure should look something like the picture below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*Nn6ev4mEAn3q3vTGCx9RyA.png" /><figcaption>Final Project Structure</figcaption></figure><p>Now let&#39;s start your project and check if EUREKA has discovered it</p><p>Go to your terminal/command prompt and navigate to the parent folder of the Customer project, make sure the folder has the pom.xml file, or else the following command won’t work.</p><pre>mvn clean spring-boot:run</pre><p>Then on your browser type the following URL Or Refresh:</p><pre><a href="http://localhost:8761/">http://localhost:8761/</a></pre><p>You should see your customer service on EUREKA Server Dashboard page like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GirloSDPq92jLrsgC5c7EQ.png" /></figure><p>You can also add a customer with Postman using the POST operation and remember to change your Request Body type to JSON.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*cuixE6YghdyyhrpVqRMYpQ.png" /></figure><p>You can also test getting all customers by using postman using the GET operation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*w0tZK5gLsWfzhAxLoDSk3g.png" /></figure><p>You can find the complete code for the Customer Microservice on the below GitHub link</p><pre><a href="https://github.com/vhutie/superdev-crm-customer.git">https://github.com/vhutie/superdev-crm-customer.git</a></pre><p><strong>3. Create ZUUL API Gateway Project, I promise this next one will be quick :-)</strong></p><p>To <strong>start from scratch</strong>, you need to head over to the below URL:</p><pre><a href="https://start.spring.io/">https://start.spring.io/</a></pre><p>And edit the group and artifact and add the dependencies needed by the project. Also, change java version to 8 and Spring boot version to 2.3.6 cause 2.4 wasn&#39;t working at the time this article was written. Please look at the image below and make sure you have similar dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8SDy5qjgw9j2Tcte_DiHIg.png" /></figure><p><strong>Dependencies explained:</strong></p><p><strong>ZUUL</strong> — Enable our project to be a ZUUL API gateway</p><p><strong>Eureka Discovery Client </strong>— Enable our project to be discovered by a Eureka server and allow our services to communicate with this service in a seamless way.</p><p><strong>Spring Boot Actuator </strong>— To enable our project to be monitored by EUREKA server and any other monitoring tools will be able to ping this service’s uptime.</p><p>After generating the project and unzipping it. Edit the Spring Boot Application class: SuperdevZuulApplication</p><pre><strong>package</strong> za.co.superdev.api;</pre><pre><strong>import</strong> org.springframework.boot.SpringApplication;</pre><pre><strong>import</strong> org.springframework.boot.autoconfigure.SpringBootApplication;</pre><pre><strong>import</strong> org.springframework.cloud.client.discovery.EnableDiscoveryClient;</pre><pre><strong>import</strong> org.springframework.cloud.netflix.zuul.EnableZuulProxy;</pre><pre><strong>import</strong> org.springframework.context.annotation.Bean;</pre><pre>@EnableZuulProxy</pre><pre>@EnableDiscoveryClient</pre><pre>@SpringBootApplication</pre><pre><strong>public</strong> <strong>class</strong> SuperdevZuulApplication {</pre><pre><strong>public</strong> <strong>static</strong> <strong>void</strong> main(String[] args) {</pre><pre>SpringApplication.<em>run</em>(SuperdevZuulApplication.<strong>class</strong>, args);</pre><pre>}</pre><pre>@Bean</pre><pre><strong>public</strong> SimpleFilter simpleFilter() {</pre><pre><strong>return</strong> <strong>new</strong> SimpleFilter();</pre><pre>}</pre><pre>}</pre><p>Add a filter class for ZUUL</p><pre><strong>package</strong> za.co.superdev.api;</pre><pre><strong>import</strong> javax.servlet.http.HttpServletRequest;</pre><pre><strong>import</strong> com.netflix.zuul.context.RequestContext;</pre><pre><strong>import</strong> com.netflix.zuul.ZuulFilter;</pre><pre><strong>import</strong> org.slf4j.Logger;</pre><pre><strong>import</strong> org.slf4j.LoggerFactory;</pre><pre><strong>public</strong> <strong>class</strong> SimpleFilter <strong>extends</strong> ZuulFilter {</pre><pre><strong>private</strong> <strong>static</strong> Logger <em>log</em> = LoggerFactory.<em>getLogger</em>(SimpleFilter.<strong>class</strong>);</pre><pre>@Override</pre><pre><strong>public</strong> String filterType() {</pre><pre><strong>return</strong> &quot;pre&quot;;</pre><pre>}</pre><pre>@Override</pre><pre><strong>public</strong> <strong>int</strong> filterOrder() {</pre><pre><strong>return</strong> 1;</pre><pre>}</pre><pre>@Override</pre><pre><strong>public</strong> <strong>boolean</strong> shouldFilter() {</pre><pre><strong>return</strong> <strong>true</strong>;</pre><pre>}</pre><pre>@Override</pre><pre><strong>public</strong> Object run() {</pre><pre>RequestContext ctx = RequestContext.<em>getCurrentContext</em>();</pre><pre>HttpServletRequest request = ctx.getRequest();</pre><pre><em>log</em>.info(String.<em>format</em>(&quot;%s request to %s&quot;, request.getMethod(), request.getRequestURL().toString()));</pre><pre><strong>return</strong> <strong>null</strong>;</pre><pre>}</pre><pre>}</pre><p>And edit the application.properties</p><pre>server.port=8081</pre><pre>#EDIT TO COMPUTER IP ADDRESS</pre><pre>eureka.client.serviceUrl.defaultZone=${EUREKA_SERVER:http://localhost:8761/eureka}</pre><pre>spring.application.name=superdev-zuul</pre><pre>zuul.routes.customer.url=http://localhost:8080</pre><pre>ribbon.eureka.enabled=false</pre><p>application.properties explained:</p><p>server.port — we are assigning a different port from the default 8080 tomcat server</p><p>zuul.routes — we are mapping ZUUL to our customer service, any request that starts with a <a href="http://localhost:8081/customer">http://localhost:8081/customer</a> will redirect to the customer’s service</p><p>ribbon.eureka.enabled — at this point we disabled the load balancing</p><p>Final project structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*ySNz-WYqKtV8z-D9_haDxQ.png" /></figure><p>Now you can start the Netflix ZUUL API Gateway and check what is on the EUREKA dashboard. Go to your terminal/command prompt and navigate to the parent folder of ZUUL project, make sure the folder has the pom.xml file, or else the following command won’t work.</p><pre>mvn clean spring-boot:run</pre><p>Then on your browser type the following URL:</p><pre><a href="http://localhost:8761/">http://localhost:8761/</a></pre><p>You should see ZUUL on the EUREKA Server Dashboard page like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qYf7A1KE3TIGF_F0u_DL8Q.png" /></figure><p>You can test your ZUUL API Gateway by trying to access customer data via ZUUL API to get all Customers’ GET request on Postman</p><pre>http://localhost:8081/customer/v1/api/customer</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*CFRwfCTcFTiiaIjVcUbjWQ.png" /></figure><p>You can find the complete code for the ZUUL API Gateway on the below GitHub link</p><pre><a href="https://github.com/vhutie/superdev-zuul.git">https://github.com/vhutie/superdev-zuul.git</a></pre><h3>Conclusion</h3><p>Part 1 of this article has finally come to an end, let’s take it step by step and make sure we have done all the necessary steps. The following article depends on this article being complete.</p><p>Part 2 will focus on changing these projects to be docker enabled, adding them to a docker-compose file, changing the customer service to persist its information from the H2 database to Postgresql, and scaling up and down of the customer service. It will be amazing 😉</p><p>Share, like and teach others…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c004552dcb31" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/scale-up-and-load-balance-a-spring-boot-microservice-with-docker-compose-persist-data-and-enable-c004552dcb31">Scale-Up and Load-Balance a Spring-Boot MicroService With Docker-Compose, Persist Data and Enable…</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Postgres Docker Image with predefined Database and Tables with permanent storage]]></title>
            <link>https://medium.com/swlh/custom-postgres-docker-image-with-predefined-database-and-tables-with-permanent-storage-2c3b44f92aad?source=rss-91d2cf71f21c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c3b44f92aad</guid>
            <category><![CDATA[custom]]></category>
            <category><![CDATA[mount]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[image]]></category>
            <dc:creator><![CDATA[Vutlhari Ndlovhu]]></dc:creator>
            <pubDate>Wed, 11 Nov 2020 12:39:29 GMT</pubDate>
            <atom:updated>2020-11-14T07:11:45.406Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>This is the first of many articles on becoming a super full stack developer. With any Information Technology system, persistence is key. In this article, we are going to learn how to set up a custom Postgres docker image with predefined databases and tables. We will also expose the database application from inside the image to the outside via port forwarding. And the last interesting part will be persisting the tables information on the outside of the container by mounting the volumes to a dedicated directory.</p><p>Please look at the overview image of what we are going to accomplish today below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LD1liCE_A08kDS1sSsBA2A.png" /></figure><p><strong>Prerequisites</strong></p><p>You need to have Docker application(Windows, Mac or Linux) installed, please download it from the URL below:</p><p><a href="https://www.docker.com/products/docker-desktop">Docker Desktop</a></p><p>Then you need to configure a volume for docker to be able to persist database or table information onto your computer’s hard drive. This will be required later on in this article.</p><p>Open your docker settings. Select Resources and click on FILE SHARING. Then you will be able to add a directory of your choosing, I’ve added /opt/workspace/nerdcode/docker as my Mac’s preferred path as indicated on the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vi4SfXn37xdbdVVcappTnA.png" /></figure><p>Next, we will pull the PostgreSQL database image from the Docker Hub repository by opening your terminal(Linux/Mac)/command prompt(Windows) and type the below command:</p><pre><em>docker pull postgres:12</em></pre><p>Once pulled, verify the image is successfully pulled locally by using the below command:</p><pre><em>docker images</em></pre><p>It should list all your docker containers. Now let’s do the more exciting part of this article.</p><h3><strong>Create your own image with connection/database settings predefined and also add a SQL script which should run once the database is up and running. For this step, you will need 2 settings files and an init script file alongside your Dockerfile. Let&#39;s start</strong></h3><ol><li>We need to access the current settings files within this default docker image, so let&#39;s start the default image in order for us to be able to copy the files.</li></ol><p>Use the command below to start your image which automatically assigns a password to the Postgres database, for this article I will leave it as a password.</p><pre><em>docker run --rm -e POSTGRES_PASSWORD=password postgres:12 &amp;</em></pre><p>2. Check your container ID to use to access the running container by running the below command:</p><pre><em>docker ps -a</em></pre><p>Results should be similar to the below image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QaP0eh9YhR2y7nLQkWQmgQ.png" /><figcaption>results from docker ps -a</figcaption></figure><p>3. Use the container ID to access the already running container by typing the below command:</p><pre><em>docker exec -it 916fc79719fc /bin/bash</em></pre><p>And change directory to the files we interested in as the image depict below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hktmsjkk0mmMd6E6JbB5Og.png" /></figure><p>We are only interested in pg_hba.conf and posrgresql.conf files</p><p>4. Exit the container by typing the command below:</p><p><em>exit</em></p><p>5. Copy files from the container to your local directory by using the following commands:</p><pre><em>docker cp 916fc79719fc:/var/lib/postgresql/data/pg_hba.conf /opt/workspace/nerdcode/docker/online</em></pre><p>and</p><pre><em>docker cp 916fc79719fc:/var/lib/postgresql/data/postgresql.conf /opt/workspace/nerdcode/docker/online</em></pre><p>6. Change the pg_hba.conf file by adding the following 2 lines at the end of the file to allow the database to accept connections from any IP addresses:</p><pre><em>host all all 0.0.0.0/0 md5<br>host all all ::/0 md5</em></pre><p>7. Change the posrgresql.conf file by locating the parameter called listen_addresses to listen to any address which might try and access this database</p><pre><em>listen_addresses = ‘*’</em></pre><p><em>Please Note: On this posrgresql.conf file, you can also change memory settings, number of connections, and logging mechanism. Not relevant to this article</em></p><p>8. Create a init script file called <strong>‘init.sql’</strong> to create a database within this Postgres, create a user, and assign the user super privileges to the database. Also, modify Postgres user password. Your file contents must contain the following:</p><pre><em>CREATE USER superdevuser;<br>CREATE DATABASE superdevdb;<br>GRANT ALL PRIVILEGES ON DATABASE superdevdb TO superdevuser;<br>ALTER USER postgres with PASSWORD ‘P@ssword1’;<br>ALTER USER superdevuser with PASSWORD ‘P@ssword1’;</em></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*seMKM5lox3zf1NdKjbcVKw.png" /></figure><p>9. Last file, <strong>‘Dockerfile’</strong>, create this file within the same directory as the previous files and add the following lines and instructions:</p><pre><em>FROM postgres:12<br>ADD pg_hba.conf /var/lib/postgresql/data/<br>ADD postgresql.conf /var/lib/postgresql/data/<br>COPY init.sql /docker-entrypoint-initdb.d/</em></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*mExlBW0nv7pWyFvr_eKTDw.png" /></figure><h3><strong>Finally, we can now create our own image, start docker container of our custom image, mount the persistence volume, and expose internal container ports to your Windows/Linux/Mac environment. Let&#39;s start…</strong></h3><ol><li>Create a custom Docker image</li></ol><p>Make sure your terminal/command prompt is within the directory where all the files were created and run the below script(don’t forget the dot at the end):</p><pre><em>docker build --t medium/database:latest .</em></pre><p>2. Check if the image exists by running the below command:</p><pre><em>docker images</em></pre><p>3. Final step, run the new image and assign it to the mount point you configured initially for permanent storage while exposing the container internal ports to the external environment</p><pre><em>docker run --rm -e POSTGRES_PASSWORD=P@ssword1 -v /opt/workspace/nerdcode/docker/data/medium:/var/lib/postgresql/data:rw -p 5432:5432 medium/database:latest &amp;</em></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_0G2KDYRMvnWPM07Bi_zdw.png" /></figure><p>4. Once the above is done, find the container ID of the started container and change the user to Postgres user and access your database. Follow the steps below:</p><pre><em>docker ps -a<br>docker exec -it f6fdacfeeb2d /bin/bash<br>su — postgres</em></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oR0a7gabs706os9urH5Y6g.png" /></figure><h3><strong>Conclusion</strong></h3><p>Now we have completed what this article was intended for, I hope you had fun and now you can do quick database setup configurations using your own image and permanently store your data. Share, like, and teach others… The next article will focus on using this article to persist Microservice Data</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c3b44f92aad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/custom-postgres-docker-image-with-predefined-database-and-tables-with-permanent-storage-2c3b44f92aad">Custom Postgres Docker Image with predefined Database and Tables with permanent storage</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>