Did you follow Spring Boot Send Email Example and ran Crowsnest? Got it to send the email monitoring notification? If so, bien hecho! But in the end we want it to work for real and not just for local testing purposes. Here, I'll demonstrate how to send the notification email via Gmail's SMTP server. This is a Spring send mail example utilising Gmail.
Spring Send Email Properties
Not wasting any time. Below is the properties you'll need to change in the Crowsnest app. Should be self explanatory. Update your application.properties as appropriate.
Obviously, we'll need a Gmail account. Once you have that, head over to manage your account (as of this writing, top right, next to the sign out button).
Your Google account page should look like below. Search for app password.
In Google App passwords, create a name for your app (I've called mine Crowsnest) and a password. This is the password you'll put in the application.properties file. This is the spring.mail.password.
Muy bien. I think that's all we'll need to do to have a Google App password for our Spring Boot app to send an email monitoring notification.
Spring Send Mail Demonstration
Ok. Run Crowsnest. If you don't know how, please jump over to Spring Boot Send Email Example and see how it is done. Visit the monitoring page. Depending on your environments.json configuration, you should have something similar like below.
In order to trigger an email notification, we'll need some site to go down. Fortunately for us, we can edit environments.json and Crowsnest will automatically pick up the changes. Thanks to Java WatchService. Hop over to Java WatchService Example for more details. So to make a site go down, I just change the port number to hit a site that does not exist. The monitoring page should look like something below.
Depending on your polling interval, I've set mine to every 10 seconds, an email will be sent. Make sure to stop the app or change environments.json back as soon as the email is sent. You don't want to spam your inbox unless you want to. The polling interval is set by a cron expression like so in the properties file.
# At every 10 seconds
cron.expression = */10 * * * * *
The moment we've been waiting for. Surely the logs the will say it has sent the email. But we will not believe it until it is sent by the SMTP server and it is in the inbox of the recipient. So let's check the Gmail sent folder and the target recipient inbox (Yahoo). I will let the images speak for themselves below.
Spring Send Mail Roundup
Since we are just mere mortals and could not afford an SMTP server, we have utilized Gmail to send our notification email for us. Just a quick Google App password setup and chucking in the correct application properties. We were able to trigger an email notification for real. Thanks for reading my Spring send mail via Gmail example.
Have you tried running your web app as a SystemD Service? This blog enhances the systemd service example in Run App as SystemD Service Example. The systemd service example written in Run App as SystemD Service Example is probably good for lower environments (e.g. development, preproduction, etc.). For production however, we'll need a few steps more. Chances are your web app sits behind a load balancer.
SystemD Service Example Setup
Here it is. Straight to the point. You can compare it with the one in Run App as SystemD Service Example. I won't be explaining the details, I will leave that to the first blog. I will explain the changes I have made.
What's changed and what's new? Most noticable is the my-web-app-curl.service. What does this service do? It simply sets the status endpoint to up as this is what is checked by the load balancer. When the load balancer sees that it is up (ie. online), it will then add the web app into the pool of available servers and route requests to it.
Let's talk about the my-web-app-curl.service unit file first. The Requires configures dependencies on other units. This unit is not started unless the dependency has been activated. That's common sense really. You can't set the service to online if my-web-app isn't fully ready. The RestartSec is the time in seconds the service will sleep before restarting the service again. The TimeoutStartSec configures the time to wait for start-up in seconds. If a daemon service does not complete start-up within the configured time, the service will be considered failed and will be shut down again. The Restart configures whether the service shall be restarted when the service process exits, is killed, or a timeout is reached. In this case, on-failure, the service will be restarted when the process exits with a non-zero exit code. Finally the most important bit, ExceStart is the command that is executed when the service is started.
Ok, time for my-web-app.service. This unit file is already explained here, Run App as SystemD Service Example. Here's what changed? The Restart has been changed to on-failure. The Before tells systemd that this service must be ran before my-web-app-curl.service. The Wants is similar to Requries but less strict. It's a weak dependency requirement. Units listed in this option will be started if the configuring unit is. However, if the listed units fail to start or cannot be added to the transaction, this has no impact on the validity of the transaction as a whole, and this unit will still be started. This is the recommended way to hook the start-up of one unit to the start-up of another unit. We are doing this weak dependency because our web app might still be loading whilst curl is being ran. We need curl to retry and the web app to completely boot up.
Enhanced SystemD Service Example Wrap Up
There you go. A quick example of chaining systemd services. As previously mentioned, if you want more details, jump to Run App as SystemD Service Example. You can now sit back and relax and see your production environment running smoothly. Congratulations, you have automated yourself out of a job.
Have you encountered this error, npm error code ERESOLVE? Right, following the setup instructions in a node app project, it was time to run npm ci. Lo and behold, the npm error code ERESOLVE error staring right into my face. Feeling confident I ask GitHub Copilot to fix my npm error. Let me share this journey.
System Used
Not a lot. Just a couple of things.
Node v22.12.0
Windows 11 Home 10.0.26200
The npm error code ERESOLVE Encounter
What is npm ci? It's a clean install of the project dependencies. It installs packages from the package-lock.json. This ensures you have the exact dependencies and version listed in that file. Unlike npm install, which can install packages from the node_modules cache. Alrighty then, let's see the error I got.
C:\workspace\shopify-app>npm ci
npm warn ERESOLVE overriding peer dependency
... more npm warn snipped...
npm error code ERESOLVE
npm error ERESOLVE could not resolve
npm error
npm error While resolving: @react-router/serve@7.14.0
npm error Found: react-router@7.13.2
npm error node_modules/react-router
npm error react-router@"^7.12.0" from the root project
npm error peer react-router@"^7.13.2" from @react-router/dev@7.13.2
npm error node_modules/@react-router/dev
npm error @react-router/dev@"^7.12.0" from the root project
npm error peer @react-router/dev@"^7.13.2" from @react-router/fs-routes@7.13.2
npm error node_modules/@react-router/fs-routes
npm error @react-router/fs-routes@"^7.12.0" from the root project
npm error 2 more (@react-router/node, @shopify/shopify-app-react-router)
npm error
npm error Could not resolve dependency:
npm error peer react-router@"7.14.0" from @react-router/serve@7.14.0
npm error node_modules/@react-router/serve
npm error @react-router/serve@"^7.14.0" from the root project
npm error peerOptional @react-router/serve@"^7.13.2" from @react-router/dev@7.13.2
npm error node_modules/@react-router/dev
npm error @react-router/dev@"^7.12.0" from the root project
npm error 1 more (@react-router/fs-routes)
npm error
npm error Conflicting peer dependency: react-router@7.14.0
npm error node_modules/react-router
npm error peer react-router@"7.14.0" from @react-router/serve@7.14.0
npm error node_modules/@react-router/serve
npm error @react-router/serve@"^7.14.0" from the root project
npm error peerOptional @react-router/serve@"^7.13.2" from @react-router/dev@7.13.2
npm error node_modules/@react-router/dev
npm error @react-router/dev@"^7.12.0" from the root project
npm error 1 more (@react-router/fs-routes)
npm error
npm error Fix the upstream dependency conflict, or retry
npm error this command with --force or --legacy-peer-deps
npm error to accept an incorrect (and potentially broken) dependency resolution.
npm error
npm error
...snipped...
Troubleshooting npm error code ERESOLVE
Upon seeing the error I scrolled up to the starting line of the error. Hmmm... what is this "npm error code ERESOLVE"? Looks like something is wrong with building the dependencies. No worries, I got GitHub Copilot running GPT6-Luna (free tier) by my side. I then tell Copilot to fix my npm ci error.
Copilot did its thing. Had several back and for with it. After like 7 attempts, no concrete solution was found. So I told copilot to stop trying to fix and restore everything back.
I went back to good old googling around. Stack Overflow finally gave me a clue. Why didn't I believe right away on the npm printed output? It did say retry command with --legacy-peer-deps. I guess I needed more information before I try it.
Fixed npm error code ERESOLVE
So I tried the --legacy-peer-deps flag. What does this flag do? This provides a way of resolving overly strict peer dependencies of packages. It will cause npm to ignore peer dependencies when building a package tree. Which is what heppens on npm versions 3 through 6. Here's how it looked like.
C:\workspace\shopify-app>npm ci --legacy-peer-deps
npm warn deprecated inflight@1.0.6: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
npm warn deprecated @humanwhocodes/config-array@0.13.0: Use @eslint/config-array instead
npm warn deprecated rimraf@3.0.2: Rimraf versions prior to v4 are no longer supported
npm warn deprecated glob@7.2.3: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me
npm warn deprecated @humanwhocodes/object-schema@2.0.3: Use @eslint/object-schema instead
npm warn deprecated node-domexception@1.0.0: Use your platform's native DOMException instead
npm warn deprecated @graphql-tools/prisma-loader@8.0.17: This package was intended to be used with an older versions of Prisma.\nThe newer versions of Prisma has a different approach to GraphQL integration.\nTherefore, this package is no longer needed and has been deprecated and removed.\nLearn more: https://www.prisma.io/graphql
npm warn deprecated eslint@8.57.1: This version is no longer supported. Please see https://eslint.org/version-support for other options.
added 748 packages, and audited 749 packages in 43s
178 packages are looking for funding
run `npm fund` for details
47 vulnerabilities (2 low, 4 moderate, 40 high, 1 critical)
To address issues that do not require attention, run:
npm audit fix
To address all issues (including breaking changes), run:
npm audit fix --force
Run `npm audit` for details.
I finally got my node_modules directory built and I can then npm run dev just fine.
C:\workspace\shopify-app>npm run dev
> dev
> react-router dev
➜ Local: http://localhost:3000/
➜ Network: use --host to expose
➜ press h + enter to show help
Final Thoughts
C:\workspace\shopify-app>npm -version
10.9.0
I'm guessing if I was on npm versions 3 through 6, I would not have encountered this error. This project was probably built with a version of npm between 3 to 6. Anyway, didn't dig deeper anymore because I already got what I wanted. In fairness to GitHub Copilot, even though it failed in fixing this error, it was successful in upgrading my a couple of my Spring Boot projects. First was upgrading Apache ActiveMQ to fix a vulnerability. Second was upgrading json-flattener because of a commons-text vulnerability. The successful ones were paid GitHub Copilot subscriptions though. That makes the scoring into:
What is a virtual host? Why would I want one? It's a way of saving costs. At minimum, you'll only need one physical or virtual machine, one backend instance and Apache. So an Apache virtual host manages the routing of IP requests to your backend instance. Allowing you to host multiple distinct websites (domain name or white labels). To visitors, it would appear that a website is running on its own dedicated server but in reality, behind the scenes, Apache uses incoming requests to serve different resources depending on the requested website. Did that make sense? Perhaps an example will make it concrete.
Tools and Assumptions
The following were the tools I used to demonstrate this Apache virtual host example. For the backend instance, I've created a simple Spring Boot web app that just serves a static page with a bit of white label handling. I'm assuminng you know your way around Windows and Windows Susbsystem Linux. Furthermore, you should be able to create your own backend instance and run it in Ubuntu. I won't be explaining how to create my Spring Boot web app in detail but I'll tell you what the code does.
A backend instance.
Windows 11 Home 10.0.26200
WSL - Ubuntu 22.04.3
Apache/2.4.52 (Ubuntu)
Good old vi and a text editor
IntelliJ IDEA 2023.3.4 (Community Edition)
How Does a Virtual Host Work
This is what we are going to do. We will have two websites (i.e. white labels). Let's pretend our website serves Japan and the Philippines market. In order to save on costs, we only have one server for both markets. We let Apache process the requests and pass it along the correct path resource to our single backend instance. Sounds simple? It is once you get the hang of it. Painful in the beginning though LOL.
Backend Instance
As I have mentioned earlier, our backend instance is a Spring Boot web app. Here's the bit that we are interested in.
@Controller
public class WelcomeController {
@GetMapping("/welcome/{country}")
public String welcome(@PathVariable String country, Model model) {
switch (country) {
case "jp":
country = "Japan";
break;
default:
country = "Philippines";
}
model.addAttribute("country", country);
return "welcome";
}
}
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Welcome Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="|Welcome to the ${country} site of Codesamples!|" />
</body>
</html>
Can you tell what this piece of code does? Right, so as you can probably tell in the WelcomeController that we check the path requested and depending on the country, we serve the specific content based on the country.
Running the Backend
For sure, you can have your own backend written in any programming language. It is up to you. The below is an excerpt from the WSL shell. Once you have it running, you should be able to curl the localhost with port. In this case curl localhost:8080 will return a result in the shell.
jpllosa@g16-gaming:/workspace/web-thymeleaf/target$ java -jar web-thymeleaf-0.0.1-SNAPSHOT.jar
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v4.1.1)
2026-08-29T15:58:02.437+01:00 INFO 9632 --- [web-thymeleaf] [ main] n.c.w.WebThymeleafApplication : Starting WebThymeleafApplication v0.0.1-SNAPSHOT using Java 17.0.18 with PID 9632 (/workspace/web-thymeleaf/target/web-thymeleaf-0.0.1-SNAPSHOT.jar started by jpllosa in /workspace/web-thymeleaf/target)
2026-08-29T15:58:02.446+01:00 INFO 9632 --- [web-thymeleaf] [ main] n.c.w.WebThymeleafApplication : No active profile set, falling back to 1 default profile: "default"
2026-08-29T15:58:03.776+01:00 INFO 9632 --- [web-thymeleaf] [ main] o.s.boot.tomcat.TomcatWebServer : Tomcat initialized with port 8080 (http)
2026-08-29T15:58:03.792+01:00 INFO 9632 --- [web-thymeleaf] [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2026-08-29T15:58:03.792+01:00 INFO 9632 --- [web-thymeleaf] [ main] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/11.0.24]
2026-08-29T15:58:03.827+01:00 INFO 9632 --- [web-thymeleaf] [ main] b.w.c.s.WebApplicationContextInitializer : Root WebApplicationContext: initialization completed in 1265 ms
2026-08-29T15:58:04.455+01:00 INFO 9632 --- [web-thymeleaf] [ main] o.s.boot.tomcat.TomcatWebServer : Tomcat started on port 8080 (http) with context path '/'
2026-08-29T15:58:04.465+01:00 INFO 9632 --- [web-thymeleaf] [ main] n.c.w.WebThymeleafApplication : Started WebThymeleafApplication in 2.924 seconds (process running for 3.648)
2026-08-29T15:58:27.138+01:00 INFO 9632 --- [web-thymeleaf] [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2026-08-29T15:58:27.138+01:00 INFO 9632 --- [web-thymeleaf] [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2026-08-29T15:58:27.139+01:00 INFO 9632 --- [web-thymeleaf] [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
Apache Virtual Host Configuration
If you've been following my blogs, chances are you have done Apache Redirect Example. Excellent, if you have done it because you'll probably already have installed the Apache Rewrite module. If you have not, please head over to Apache Redirect Example and follow the Complex Apache Redirect section. And if you are too lazy to pop over there, then here's what I did. We also need the Proxy and HTTP Proxy modules. Restart Apache after it is installed. To check what modules you have, head over to /etc/apache2/mods-enabled directory.
jpllosa@g16-gaming:/etc/apache2/mods-enabled$ sudo a2enmod rewrite
[sudo] password for jpllosa:
Enabling module rewrite.
To activate the new configuration, you need to run:
systemctl restart apache2
jpllosa@g16-gaming:/etc/apache2/mods-enabled$ ls
access_compat.load authn_file.load autoindex.load env.load mpm_event.load rewrite.load
alias.conf authz_core.load deflate.conf filter.load negotiation.conf setenvif.conf
alias.load authz_host.load deflate.load mime.conf negotiation.load setenvif.load
auth_basic.load authz_user.load dir.conf mime.load reqtimeout.conf status.conf
authn_core.load autoindex.conf dir.load mpm_event.conf reqtimeout.load status.load
jpllosa@g16-gaming:/etc/apache2/mods-enabled$ sudo a2enmod proxy proxy_http
[sudo] password for jpllosa:
Enabling module proxy.
Considering dependency proxy for proxy_http:
Module proxy already enabled
Enabling module proxy_http.
To activate the new configuration, you need to run:
systemctl restart apache2
jpllosa@g16-gaming:/etc/apache2/mods-enabled$ ls
access_compat.load authn_file.load autoindex.load env.load mpm_event.load proxy_http.load setenvif.load
alias.conf authz_core.load deflate.conf filter.load negotiation.conf reqtimeout.conf status.conf
alias.load authz_host.load deflate.load mime.conf negotiation.load reqtimeout.load status.load
auth_basic.load authz_user.load dir.conf mime.load proxy.conf rewrite.load
authn_core.load autoindex.conf dir.load mpm_event.conf proxy.load setenvif.conf
jpllosa@g16-gaming:/etc/apache2/mods-enabled$ sudo systemctl restart apache2
Next is the per website Apache virtual host configuration. Create a similar file like below in your /etc/apache2/sites-available directory. Remember we are still in WSL Ubuntu land. You can name it whatever you like. I do hope it is descriptive though. Below is the virtual host configuration for the Japan website. You may skip copying the comments but I just straight up copied it over from 000-default.conf. Make another config file for the Philippines website. Should be the same except ServerName or you could say the "jp" bits become "ph".
jpllosa@g16-gaming:/etc/apache2/sites-available$ cat codesamples_jp.conf
<VirtualHost *:80>
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.
ServerName codesamples.jp
ServerAdmin webmaster@localhost
#DocumentRoot /var/www/html
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn
ErrorLog ${APACHE_LOG_DIR}/codesamples-jp-error.log
CustomLog ${APACHE_LOG_DIR}/codesamples-jp-access.log combined
# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf
ProxyPreserveHost On
ProxyPass / http://localhost:8080/welcome/jp
ProxyPassReverse / http://localhost:8080/welcome/jp
</VirtualHost>
jpllosa@g16-gaming:/etc/apache2/sites-available$ cat codesamples_ph.conf
<VirtualHost *:80>
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.
ServerName codesamples.ph
ServerAdmin webmaster@localhost
#DocumentRoot /var/www/html
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn
ErrorLog ${APACHE_LOG_DIR}/codesamples-ph-error.log
CustomLog ${APACHE_LOG_DIR}/codesamples-ph-access.log combined
# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf
ProxyPreserveHost On
ProxyPass / http://localhost:8080/welcome/ph
ProxyPassReverse / http://localhost:8080/welcome/ph
</VirtualHost>
What did you notice? How are we reaching our backend instance? As you can see, we are adding the path variable based on country or should I say Apache is adding it so our backend will know what content to serve.
Below is the trail of commands you'll possibly do. After you have two Apache virtual host config files, you'll need to enabled it (e.g. a2ensite) and disabled the default Apache config (e.g. a2dissite. Obviously, reload Apache to apply the changes you did.
jpllosa@g16-gaming:/etc/apache2/sites-available$ sudo cp codesamples_jp.conf codesamples_ph.conf
jpllosa@g16-gaming:/etc/apache2/sites-available$ sudo vi codesamples_ph.conf
jpllosa@g16-gaming:/etc/apache2/sites-available$ sudo a2ensite codesamples_jp.conf
Enabling site codesamples_jp.
To activate the new configuration, you need to run:
systemctl reload apache2
jpllosa@g16-gaming:/etc/apache2/sites-available$ sudo a2ensite codesamples_ph.conf
Enabling site codesamples_ph.
To activate the new configuration, you need to run:
systemctl reload apache2
jpllosa@g16-gaming:/etc/apache2/sites-available$ sudo a2dissite 000-default.conf
Site 000-default disabled.
To activate the new configuration, you need to run:
systemctl reload apache2
jpllosa@g16-gaming:/etc/apache2/sites-available$
Administrative Ubuntu Configuration
We're not done yet. See? I told you it was painful. Patience, we are nearly there. We are halfway there. What's left is getting traffic to route correctly. First is the /etc/hosts file. Update your hosts file as below. You can replace it with your own domain name as long as it matches your Apache virtual host configuration.
jpllosa@g16-gaming:/etc$ cat /etc/hosts
# This file was automatically generated by WSL. To stop automatic generation of this file, add the following entry to /etc/wsl.conf:
# [network]
# generateHosts = false
127.0.0.1 localhost
127.0.0.1 codesamples.jp
127.0.0.1 codesamples.ph
# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
jpllosa@g16-gaming:/etc$
What this does is route requests to codesample.ph and codesample.jp to your Ubuntu box. Next is we need to know what the IP of our Linux box is. We need this IP to configure our Windows machine to route traffic to our Linux box. Here's my IP but it could be different in your system.
jpllosa@g16-gaming:/etc$ ip addr
1: lo: mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet 10.255.255.254/32 brd 10.255.255.254 scope global lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: mtu 1492 qdisc mq state UP group default qlen 1000
link/ether 00:15:5d:8a:ce:ae brd ff:ff:ff:ff:ff:ff
inet 172.18.182.45/20 brd 172.18.191.255 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::215:5dff:fe8a:ceae/64 scope link
valid_lft forever preferred_lft forever
When requests come in, you can tail the Apache log files. Here's an example of where the log files are located.
Now that we got the IP, let's ping it to check connectivity. When we have connectivity, update the Windows hosts file. This will tell Windows where to route requests to our example domains. You'll need admin priviledges to update the hosts file.
C:\>ping 172.18.182.45
Pinging 172.18.182.45 with 32 bytes of data:
Reply from 172.18.182.45: bytes=32 time=1ms TTL=64
Reply from 172.18.182.45: bytes=32 time<1ms TTL=64
Reply from 172.18.182.45: bytes=32 time<1ms TTL=64
Reply from 172.18.182.45: bytes=32 time<1ms TTL=64
Ping statistics for 172.18.182.45:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 1ms, Average = 0ms
C:\Windows\System32\drivers\etc>type hosts
...snipped...
172.18.182.45 codesamples.jp
172.18.182.45 codesamples.ph
Apache Virtual Host Demonstration
Congratulations, you made it this far. Now, the time has come to see all the work we have done. Java web app is running? Check. Apache restarted with the correct configurations? Check. Ubuntu and Windows hosts file updated? Check. Very good! Let's hit the domains. Fire up your browser and go to your website. Here are a couple of screen grabs of the two example websites with corresponding network tab open and tailing the Apache access logs at the same time. As you will experience if you are trying this out, the logs move as soon as you request for your website. Which tells us we have routed things correctly since the request has reached it's target destination. Bravo, well done!
Apache Virtual Host Summary
There you have it. Was that fun for you? You have managed the routing of IP requests to your backend. You have hosted two distinct websites and the visitors wouldn't know it was only one Java web app working behind the scenes. Have a happy virtual hosting.
Do you need to support multiple environments? Tired of spinning up instances? Perhaps custom JSON serialization and deserialization can help.
The Ask
Here's the situation. You got a web API and then one day your customer wants to roll out two more development environments. This will result in three instances hitting your web API. Production and preproduction environments remain a one to one relationship. As it stands, your IDs are integers in all environments. Constraint number one, you can't afford to spin up more development environments to match your customer's new development instances due to limited staff. Second, can't afford to spin more infrastructure. Third, you don't want to maintain more pods/servers. Lastly, in the development environment, you need to know which development environment the ID came from.
The Solution
The solution is custom JSON serialization and deserialization of course. LOL, this is what the blog is all about. Anyway, we need the web API to be able to accept a number and a string for incoming requests. This way, when deployed to higher environments (e.g. production and preproduction), incoming requests with IDs that are numbers will not break things.
Now, when passing the ID down the line (e.g. internal systems), we need to make sure a number and string can be passed as either of both types to make sure nothing breaks. Clear so far? How's your imagination doing? Can you imagine it now? Got your head wrapped around it?
As for persistence, that's another story but ALTER TABLE should do the trick. Also, this blog is about custom JSON serialization and deserialization. The database operations are another blog in itself. So not talking about that.
Custom JSON Deserialization
Below is the test to make sure customerId is deserialized as strings.
//... imports snipped...
@SpringBootTest
public class RequestDtoTest {
@Test
public void customerIdNumberToString() {
String jsonInput = "{\"customerId\":12345}";
RequestDto dto = new ObjectMapper().readValue(jsonInput, RequestDto.class);
assertNotNull(dto.getCustomerId());
assertEquals("12345", dto.getCustomerId());
}
@Test
public void customerIdMaintainedAsString() {
String jsonInput = "{\"customerId\":\"dev1-12345\"}";
RequestDto dto = new ObjectMapper().readValue(jsonInput, RequestDto.class);
assertNotNull(dto.getCustomerId());
assertEquals("dev1-12345", dto.getCustomerId());
}
}
Clear enough? Just imagine the web API received a request. As you can see it is able to accept a number (e.g. 12345 non development environments) and a string (e.g. dev1-12345 for the development environments). Below are the code that handles the custom JSON deserialization. First is to create your custom JSON deserializer of course. Pretty straight forward wouldn't you say? If the token is a string, no need to cenvert. Just return it right away. If it is a number, convert to string. Anything else, return as string.
Here's a tip. Actually, we didn't need to explicitely do this. Why you ask?, Because Jackson coerces values in strings. It's worth advocating this explicit approach. Makes it clearer to the future developers as to what's going on. Also limit the type to only integers can be coerced.
//... imports snipped...
public class NumberToStringDeserializer extends StdDeserializer {
public NumberToStringDeserializer() {
super(String.class);
}
@Override
public String deserialize(JsonParser parser, DeserializationContext context) {
JsonToken token = parser.currentToken();
if (token == JsonToken.VALUE_NULL) {
return null;
}
if (token == JsonToken.VALUE_STRING) {
return parser.getString();
}
if (token == JsonToken.VALUE_NUMBER_INT) {
return parser.getNumberValue().toString();
}
// anything else
return (String) context.handleUnexpectedToken(String.class, parser);
}
}
Finally, is to declare the deserializer (@JsonDeserialize(using = NumberToStringDeserializer.class) in your POJO. Well done. You have got yourself a custom JSON deserializer.
//... imports snipped...
public class RequestDto {
@JsonDeserialize(using = NumberToStringDeserializer.class)
@JsonProperty("customerId")
private String customerId;
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
@Override
public String toString() {
return "RequestDto{" +
"customerId='" + customerId + '\'' +
'}';
}
}
Custom JSON Serialization
Below is the test to make sure transactionId is serialized as a string (i.e. for dev environments) if it can't be converted into a number (i.e. for prod and preprod environments).
//... imports snipped...
@SpringBootTest
public class ResponseDtoTest {
@Test
public void transactionIdNumberToString() {
ResponseDto dto = new ResponseDto();
dto.setTransactionId("54321");
String expectedJson = "{\"transactionId\":54321}";
String actualJson = new ObjectMapper().writeValueAsString(dto);
assertEquals(expectedJson, actualJson);
}
@Test
public void transactionIdMaintainedAsString() {
ResponseDto dto = new ResponseDto();
dto.setTransactionId("dev2-54321");
String expectedJson = "{\"transactionId\":\"dev2-54321\"}";
String actualJson = new ObjectMapper().writeValueAsString(dto);
assertEquals(expectedJson, actualJson);
}
}
Right, so if we can convert the value into a number, we do it. Otherwise, send it over the wire as a string.
//... imports snipped...
public class StringToNumberSerializer extends StdSerializer {
public StringToNumberSerializer() {
super(String.class);
}
@Override
public void serialize(String value, JsonGenerator generator, SerializationContext context) throws JacksonException {
try {
generator.writeNumber(Integer.parseInt(value));
} catch (NumberFormatException e) {
generator.writeString(value);
}
}
}
Lastly, declare the serializer (@JsonSerialize(using = StringToNumberSerializer.class) in your POJO. Amazing! You've got a custom JSON serializer.
//... imports snipped...
public class ResponseDto {
@JsonSerialize(using = StringToNumberSerializer.class)
private String transactionId;
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
@Override
public String toString() {
return "ResponseDto{" +
"transactionId='" + transactionId + '\'' +
'}';
}
}
JSON Custom Deserialize/Serialize Conclusion
I'm using IntelliJ IDEA 2023.3.4 (Community Edition). You should be able to run the unit tests and you should have something like below.
There you have it. A straight forward custom JSON deserialization and serialization. Making you save money and use less resources. You can grab the repo from GitHub.
As a software developer nowadays, we are expected to pick things up rather quickly. You can be assigned to a JIRA ticket to make changes to an app written in a programming language you are not that familiar with. It's normal to compare or ask for example how is it done in Go when you are used to the Java way. What do you do? Pass up on that task or jump straight in? You can refuse the task and pick something else but I wonder how management would see that.
Anyway, here's a look at unit testing in Go with a Java background. This Go repo, go-unit-testing is a port of this Java repo, tdd-junit.
Tools
Visual Studio Code 1.126 with a Go extension
Windows 11 Home 10.0.26200
Go version 1.22.1
Those are the tools I used to build this example.
Let's Go Unit Testing
Go has a built-in package for testing and surprisingly, it's called testing. It is part of Go's standard library. Comparing to Java, JUnit is not part of the standard library.
Below is the function that we will test. It's under the mathfun package.
package mathfun
func GetGcf(x int, y int) int {
if y == 0 {
return x
} else {
return GetGcf(y, x%y)
}
}
Let's write the code that will test our function. Under the mathfun package, create the file math_fun_test.go. The _test.go tells Go that this file contains test functions. Below is the code of the said file:
package mathfun
import (
"testing"
)
func TestWithTwoPositiveNumbers(t *testing.T) {
actual := GetGcf(12, 16)
expected := 4
if expected != actual {
t.Errorf(`GCF of 12 and 16, expected = %d, actual = %d`, expected, actual)
}
}
func TestWithZero(t *testing.T) {
actual := GetGcf(0, 6)
expected := 6
if expected != actual {
t.Errorf(`GCF of 0 and 6, expected = %d, actual = %d`, expected, actual)
}
}
Basically, the above code exercises the GetGcf function. Making sure to try and run every line of code in it. It checks for correct return values.
Ok, unlike Java, it's function names and not annotations (e.g. @Test) but still the function naming is DAMP. Test function names have the form of TestName, where Name is the DAMP (Descriptive and Meaning Phrase) of the test. The testing.T type parameter is used for logging and reporting your test result.
One thing that's been ingrained in me is the assertEquals. So it was surprising that Go didn't have an assert function but just do an if statement and based on that error out. I kinda like assert equals expected actual thing.
Running Go Unit Tests
The "go test" command. Executes all test function (names beginning with Test) it could find inside files ending in _test.go.
C:\workspace\go-unit-test\mathfun> go test
PASS
ok go-unit-test/mathfun 0.578s
go text -v for verbose output
C:\workspace\go-unit-test\mathfun> go test -v
=== RUN TestWithTwoPositiveNumbers
--- PASS: TestWithTwoPositiveNumbers (0.00s)
=== RUN TestWithZero
--- PASS: TestWithZero (0.00s)
PASS
ok go-unit-test/mathfun 0.556s
The command below runs the test in current directory. The last bit will run tests in all directories.
C:\workspace\go-unit-test\mathfun> go test .
ok go-unit-test/mathfun 0.550s
C:\workspace\go-unit-test\mathfun> cd ..
C:\workspace\go-unit-test> go test .
? go-unit-test [no test files]
C:\workspace\go-unit-test> go test ./...
? go-unit-test [no test files]
ok go-unit-test/mathfun (cached)
As you can see above, Go caches successful test results to avoid running it again. The rule is, if the test binary is the same and there are no flags in the command line telling Go to rerun the test, then it will pull the cached test. Changes to your code or test code invalidates the cached test result so this isn't much of a big deal but if you really want to invalidate the cached test results, you can go clean -testcache
The command below does per package testing and the last two run the test per function.
C:\workspace\go-unit-test> go test ./mathfun
ok go-unit-test/mathfun (cached)
C:\workspace\go-unit-test> go test -run ^TestWithTwoPositiveNumbers$ go-unit-test/mathfun
ok go-unit-test/mathfun 0.566s
C:\workspace\go-unit-test> go test -v -run ^TestWithTwoPositiveNumbers$ go-unit-test/mathfun
=== RUN TestWithTwoPositiveNumbers
--- PASS: TestWithTwoPositiveNumbers (0.00s)
PASS
ok go-unit-test/mathfun 0.527s
If you need more information on the go test command, it is right at your finger tips.
C:\workspace\go-unit-test\mathfun> go help test
usage: go test [build/test flags] [packages] [build/test flags & test binary flags]
'Go test' automates testing the packages named by the import paths.
It prints a summary of the test results in the format:
...snipped...
Go Unit Testing Summary
At the end of the day. Comparing it to JUnit, I'd say same nail pounded by a different hammer. Same principles really. As much as possible, all code has to be exercised and make sure the actual output is the same as the expected output.
Now that you got your monitoring up and running, what's next? Do you relax, put your feet up and read Jack Reacher Tripwire? I'm sure your boss will say "Can this notify us when something is wrong? Like send an email or something. There you go. This bit is about adding that send email functionality.
The code is in here, Crowsnest and here's what changed, pull request. Anyway, let's talk about what was added for this monitoring app to be able to send an email.
Additional Dependency
With the addition of below in the pom.xml, you receive Spring's sending email bells and whistles. Spring Boot will provide auto-configuration and abstraction for sending email by using the JavaMailSender interface.
You might want to customized the configuration of JavaMarlSender. It can be added in the application.properties file using the spring.mail namespace. Some default timeout values are infinite, so you might want to add some properties like below to avoid freezing your app because of an unresponsive SMTP server.
Here's the meat of the send email operation. By default, if spring.mail.host and the Spring Mail libraries are defined, you can inject JavaMailSender automatically. The email sender proxy defined will be the sender. I think the variables are descriptive enough as to what it is for, isn't it? We got a "to", our destination email. Subject of the email and the text which will be the body of the email. Clear enough? Great!
package net.codesamples.crowsnest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
@Component
public class EmailService {
@Autowired
private JavaMailSender mailSender;
@Value("${email.sender.proxy}")
private String emailSenderProxy;
public void sendEmailMessage(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(emailSenderProxy);
message.setTo(to);
message.setSubject(subject);
message.setText(text);
mailSender.send(message);
}
}
Spring Boot Send Email Trigger
Next is when do we want it to send an email? Of course as soon as something goes down. Fairly simple, just @Autowire the EmailService component and call the send email message method in our SchedulePings class.
We have a feature flag as well. So if emailFeatureEnabled is set to true, we send the email. Otherwise we don't.
Spring Boot Send Email Test
Alright, time to see if this send email thing works. First thing we'll need is an SMTP server that will handle emails being sent. I'm using an old version of smtp4dev but there is a new one which is definitely better. Anyway, run Crowsnest and bring a system down that it is monitoring. You should be able to figure that out. Smtp4dev will look like below.
Email details will look like below.
Spring Boot Send Email Wrap Up
Congratulations. Your app can now spam the hell out of the monitoring team. To recap, we added Spring Boot's starter mail dependency. Then added the properties. After that, created a component to handle the email service. Lastly, find an entry point in our monitoring code as to when to invoke sending the email. Short and sweet.
Have you ever encountered Spring's WebClient throwing a "failed to resolve 'hostname' after x queries" error?. Well, if you ran my Crowsnest project prior to my latest merge, then chances are you may have. Especially, if you ran it inside your internal network. Here's what the error looks like.
Spring WebClient Failed to Resolve Cause
As the error states, the target hostname can't be resolved. It is a DNS thing. By default WebClient uses the JVM implementation to resolve the hostname. In my case, my Linux box was inside a VPN and somehow Java's standard networking library (e.g. java.net.InetAddress) was ignoring the local DNS settings. Worked fine when the target was accessible in the Internet.
Spring WebClient Failed to Resolve Sorted
To solve this dilemma, we simple change the default hostname resolver to something that can do the job. Luckily, there is Netty's DNS resolver we can use. It is io.netty.resolver.DefaultAddressResolverGroup, and we just tell Spring to use it. So WebClient will now use Netty's DNS Resovler thru HttpClient and no longer the default JVM implementation. We'll need to change a couple of things in our code.
Create a new WebClient that will be injected in other parts of the code.
package net.codesamples.crowsnest;
// ... other imports snipped
import io.netty.resolver.DefaultAddressResolverGroup;
import reactor.netty.http.client.HttpClient;
@SpringBootApplication
@EnableScheduling
public class CrowsnestApplication {
public static void main(String[] args) {
SpringApplication.run(CrowsnestApplication.class, args);
}
@Bean
public WebClient webClient() {
HttpClient httpClient = HttpClient.create().resolver(DefaultAddressResolverGroup.INSTANCE);
return WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(httpClient)).build();
}
}
Use the bean in other parts of the code thru @Autowired.
package net.codesamples.crowsnest;
// ... impoerts snipped
@Component
public class ScheduledPings {
private static final Logger log = LoggerFactory.getLogger(ScheduledPings.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Autowired
EnvironmentConfigurationWatcher environmentConfigurationWatcher;
@Autowired
SimpMessagingTemplate simpMessagingTemplate;
@Autowired
private WebClient webClient;
private List internalEnvironmentList = new ArrayList<>();
private ObjectMapper mapper = new ObjectMapper();
@Scheduled(cron = "${cron.expression}")
public void pinger() {
log.info("The time is now {}", dateFormat.format(new Date()));
List environmentList = environmentConfigurationWatcher.getEnvironmentList();
log.info("Environment list: {}", environmentList);
for (Environment environment : environmentList) {
for (App app : environment.getApps()) {
Mono mono = webClient.get()
.uri(app.getUrl())
.exchangeToMono(clientResponse -> {
HttpStatusCode statusCode = clientResponse.statusCode();
if (statusCode.is2xxSuccessful()) {
app.setStatus("up");
}
log.info("StatusCode: {} = {}", statusCode, app.getUrl());
return clientResponse.bodyToMono(String.class);
})
.onErrorResume(Exception.class, exception -> {
log.info("Exception {}", exception.getMessage());
app.setStatus("down");
return Mono.empty();
});
mono.subscribe();
}
}
// ... code snipped
}
Spring WebClient Failed to Resolve Fixed
Things should now work again. If it does not, let me know.
Here we go. You got an old web app that start/stop/restart using initd scripts. This was well and good in the CentOS days. After some OS updates here and there, your web app now runs on Rocky 9.7. Trouble is on VM reboots, your web app does not start up automatically and you have 10 apps on the box. From time to time, CI/CD breaks because your web app process goes on zombie mode and you'll have to manually kill it.
What can you do? Move it from an initd to a systemd service. As to the why the Linux folks replaced or moved from initd to systemd, I'll let you google that around. Here are the steps to make your app run as a systemd service.
All .service file start with a Unit section which provides basic information about the service. The Description must not exceed 80 characters and must describe the service. The After tells systemd to only activate this service after this prerequisite. In this example, the service is activated after network connectivity is established. We have disabled any kind of rate limiting by setting StartLimitIntervalSec to 0. This rate limiting works in conjunction with Restart.
The Service section provides instructions on how to control the service. The simple Type means to start the service without any special considerations. The ExecStart clearly shows the command to run to start the service. The full path to the command and arguments are declared. User specifies the user under which the service should run. RestartSec configures the time in seconds to sleep before restarting the service. Restart is set to always, as the word says, the service will be restarted no matter what (e.g. process is terminated by a signal, non-zero exit code, termination due to out of memory, etc). There is a default timeout for starting, stopping and aborting of units, as well as a default time to sleep between automatic restarts of units. If the restart times out after several tries, the system will not try to restart the service. Therefore, we have set above StartLimitIntervalSec to 0, so it will try to restart the service to infinity and beyond.
WantedBy is used to create symlinks in .wants/ directories when the service is enabled. In this case, a symlink will be created under multi-user.target.wants. This indicates that the service should be started as part of the multi-user system.
Copy the above service file to where systemd service file reside. As seen below.
[jpllosa@rocky-balboa system]$ pwd
/etc/systemd/system
[jpllosa@rocky-balboa system]$ ls -ali
total 24
67738686 drwxr-xr-x. 10 root root 4096 Mar 17 13:27 .
863730 drwxr-xr-x. 6 root root 4096 Feb 10 13:45 ..
67824144 drwxr-xr-x. 2 root root 65 Feb 13 13:43 basic.target.wants
67750396 lrwxrwxrwx. 1 root root 37 Feb 10 12:27 ctrl-alt-del.target -> /usr/lib/systemd/system/reboot.target
67824045 lrwxrwxrwx. 1 root root 41 Feb 10 12:28 dbus-org.fedoraproject.FirewallD1.service -> /usr/lib/systemd/system/firewalld.service
67823100 lrwxrwxrwx. 1 root root 57 Feb 10 12:28 dbus-org.freedesktop.nm-dispatcher.service -> /usr/lib/systemd/system/NetworkManager-dispatcher.service
67750469 lrwxrwxrwx. 1 root root 43 Feb 10 12:27 dbus.service -> /usr/lib/systemd/system/dbus-broker.service
67750393 lrwxrwxrwx. 1 root root 41 Feb 10 12:29 default.target -> /usr/lib/systemd/system/multi-user.target
67736707 -rw-r--r--. 1 root root 394 Mar 17 13:27 my-web-app.service
905723 drwxr-xr-x. 2 root root 32 Feb 10 12:27 getty.target.wants
68554611 drwxr-xr-x. 2 root root 56 Feb 13 13:43 graphical.target.wants
34039637 drwxr-xr-x. 2 root root 4096 Mar 17 13:32 multi-user.target.wants
67823101 drwxr-xr-x. 2 root root 48 Feb 10 12:28 network-online.target.wants
67750466 drwxr-xr-x. 2 root root 71 Feb 10 12:28 sockets.target.wants
101399263 drwxr-xr-x. 2 root root 4096 Feb 10 12:28 sysinit.target.wants
956462 drwxr-xr-x. 2 root root 56 Feb 10 12:28 timers.target.wants
Starting and Enabling the Web App
Now that the service is ready. Let's start up the web app.
sudo systemctl start web-app
If there are no error, you can then enable the web app so it will start at boot. You don't need to worry about reboots. The web app will automatically start up now.
You can now sit back and relax. No more panic mode after VM reboots and when other people complain why things aren't working as they are supposed to. Goodbye zombie processes. Congratulations, you have automated yourself out of a job.
Alright, now that you got a docker image in the previous example, Dockerize Spring Boot App Example, what now? The most obvious next step is to spin up the docker image in a Kubernetes cluster. But GKE (Google Kubernetes Engine) is bloody expensive for us mere mortals. Luckily we can practice Kubernetes stuff with Docker Desktop.
First up is to start a Kubernetes cluster via Docker Desktop. Should just be a bunch of clicks. I just chose a single node cluster (Kubeadm). You should have something like below:
And if you have Lens K8S IDE. You'll have something like below.
Deploy to Kubernetes
First, let's check our image (docker images). Like so:
C:\workspace>docker images
i Info → U In Use
IMAGE ID DISK USAGE CONTENT SIZE EXTRA
crowsnest:v1.0.0 b9bfb190828e 567MB 197MB U
Let's make sure we deploy to docker desktop kubernetes.
C:\workspace>kubectl config use-context docker-desktop
Switched to context "docker-desktop".
And the fun starts, create a deployment.
C:\workspace>kubectl create deployment crowsnest --image=crowsnest:v1.0.0
deployment.apps/crowsnest created
After deployment, take a look at Lens and Docker Desktop.
Or if you like CLI.
C:\workspace>kubectl get pods
NAME READY STATUS RESTARTS AGE
crowsnest-f56bb85ff-t9dn9 1/1 Running 0 28m
Well and good so far. But our web app is not reachable from the browser yet. We need to expose the port of the pod so we can get to the web app. Do note that your pod name might be different from this example.
C:\workspace>kubectl expose pod crowsnest-f56bb85ff-t9dn9 --port=8080 --name=crowsnest --type=LoadBalancer
service/crowsnest exposed
C:\workspace>kubectl get services
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
crowsnest LoadBalancer 10.100.27.69 localhost 8080:31912/TCP 97s
kubernetes ClusterIP 10.96.0.1 443/TCP 4d3h
You should have something like below.
Perfecto! We should be able to access Crowsnest on the browser now. localhost:8080.
Thank you Docker Desktop for helping us save money by practicing kubectl stuff with you, instead of the expensive GKE. Deploying to GKE should be similar. Just need to point kubectl to GKE.
Undeploy from Kubernetes
Most importantly when doing this on a paid Kubernestes service, don't forget to delete the pod, service, deployment, etc. GKE billing is astronomical (delete the project too to be sure!) Here are the commands to undo what you've done.
C:\workspace>kubectl delete service crowsnest --now
service "crowsnest" deleted from default namespace
C:\workspace>kubectl delete deployment crowsnest --now
deployment.apps "crowsnest" deleted from default namespace
C:\workspace>kubectl get services
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 443/TCP 4d3h
C:\workspace>kubectl get pods
No resources found in default namespace.
Deploy to Kubernetes Wrap Up
Yes, we did all of the above steps manually. Yes, this can all be automated. But before we automate stuff, we have to do it manually. For example, you can create a GitHub action workflow to do all of the above steps to spin up your docker image to GKE, just with a yaml file. That would be another story. Happy spinning!
One of the benefits of a dockerize app (dockerize is synonymous with containerization, just like googling is to web searching) is the ease of deployment to different environments. Once you got that docker image built, you can stick it in any environment you like. Shall we dockerize your Spring Boot app? Here's a quick example.
Before we can run the docker file, let's build the project first. Run, mvn clean install in IntelliJ or via command line. That should create a target directory. Now, let's take a look at the Dockerfile found at the root directory.
FROM eclipse-temurin:17-jdk-alpine
RUN addgroup -S crowsnest && adduser -S crowsnest -G crowsnest
USER crowsnest:crowsnest
COPY docker-files/ app-files
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} crowsnest.jar
ENTRYPOINT ["java", "-jar", "crowsnest.jar", "--spring.config.location=/app-files/application.properties"]
What does above file mean? What will it do? FROM means that this is the base image. Our crowsnest image will extend from this image. Docker Hub contains a lot of Docker images that are suitable as base images. In this case our base image is built by Eclipse Temurin loaded with OpenJDK 17.
The RUN command will execute the Alpine Linux shell commands addgroup and adduser. The end result is a user called crowsnest belonging to the crowsnest group. This user will run the Crowsnest Spring Boot app. We don't want root running the app. The -S is a flag for system services or daemon group.
The USER command will set the user name and user group to crowsnest as the default user and group. This user is used for succeeding RUN, ENTRYPOINT, and CMD commands.
The COPY command, as it says, will copy the files in our local docker-files directory to the app-files directroy in the Alpine Linux image.
The ARG command defines the JAR_FILE variable that is passed at build time to the builder.
The next COPY command, copies all the jar files from the target directory into a single jar called crowsnest.jar.
Lastly ENTRYPOINT command configures the container to run as an executable. In this case, it will run java with the -jar and --spring.config.location parameters.
Right, let's build the image using the docker build command. Like so:
C:\workspace\crowsnest>docker build -t crowsnest:v1.0.0 .
[+] Building 5.2s (8/8) FINISHED docker:desktop-linux
=> [internal] load build definition from Dockerfile
The above command builds the crowsnest image with the image identifier (i.e tag) crowsnest:v1.0.0 on the current path. I sometimes add the option --no-cache to not use cache when building the image. After a successful build, you should have something like below. Old school way is docker images on the CLI (Command Line Interface.
Running the Docker Image
Righto, let's see this image in action. Go to the command line and run docker run -p 8080:8080 crowsnest:v1.0.0. This command will create and run a new container from the image tagged crowsnest:v1.0.0 exposing port 8080 and routing incoming requests to Crowsnest running on port 8080. In the words, the first 8080 is the container port number. The second is your app's port number. You should have something like below.
C:\workspace\crowsnest>docker run -p 8080:8080 crowsnest:v1.0.0
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.5.9)
2026-02-18T15:26:52.406Z INFO 1 --- [crowsnest] [ main] n.c.crowsnest.CrowsnestApplication : Starting CrowsnestApplication v0.0.1-SNAPSHOT using Java 17.0.17 with PID 1 (/crowsnest.jar started by crowsnest in /)
2026-02-18T15:26:52.409Z INFO 1 --- [crowsnest] [ main] n.c.crowsnest.CrowsnestApplication : No active profile set, falling back to 1 default profile: "default"
2026-02-18T15:26:53.293Z INFO 1 --- [crowsnest] [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port 8080 (http)
2026-02-18T15:26:53.307Z INFO 1 --- [crowsnest] [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2026-02-18T15:26:53.307Z INFO 1 --- [crowsnest] [ main] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/10.1.50]
2026-02-18T15:26:53.343Z INFO 1 --- [crowsnest] [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2026-02-18T15:26:53.344Z INFO 1 --- [crowsnest] [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 878 ms
2026-02-18T15:26:53.796Z INFO 1 --- [crowsnest] [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page: class path resource [static/index.html]
2026-02-18T15:26:53.974Z INFO 1 --- [crowsnest] [ main] o.s.m.s.b.SimpleBrokerMessageHandler : Starting...
If you are not old school, the docker desktop UI will look like so:
You can start/stop the image from running via the Actions button. Chances are you might experience some connectivity problems. Can't connect to an API or database. Click on the three dots then "Open in terminal". This should give you a shell prompt like below. As you can see, we are running Alpine Linux. Remember FROM eclipse-temurin:17-jdk-alpine? On the root directory is app-files and crowsnest.jar. Built with the following commands COPY docker-files/ app-files and COPY ${JAR_FILE} crowsnest.jar. Here, you can try ping, curl, wget, telnet, etc. to check connectivity. Excellent!
Dockerize a Spring Boot App
Outstanding. We have built and ran a docker image. We can spin this image up in any environment we like. To recap, we build our image from a base image then add what we need like the necessary configuration files, the application itself, etc. Finally, we specify our app as the default executable. Happy dockerizing!