Skip to main content

Chapter 1: Preparation for Production

Introduction​

Before deploying, you need to prepare your application. This chapter covers packaging, profiles, and configuration management.


🎯 Chapter Objectives​

By the end of this chapter, you will know how to:

  1. ✅ Create an executable JAR
  2. ✅ Configure Spring profiles
  3. ✅ Externalize configuration
  4. ✅ Manage secrets securely
  5. ✅ Optimize for production

1. Packaging: JAR vs WAR​

Spring Boot creates a fat JAR containing everything:

# Build
mvn clean package

# Run
java -jar target/myapp-1.0.0.jar

Advantages:

  • ✅ Embedded Tomcat server
  • ✅ Easy to deploy
  • ✅ Portable
  • ✅ Perfect for Docker

WAR (External server)​

To deploy on existing Tomcat/JBoss:

<!-- pom.xml -->
<packaging>war</packaging>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
// Modify the main class
@SpringBootApplication
public class Application extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Application.class);
}

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

Recommendation​

JAR for:
- Docker / Kubernetes
- Cloud (Heroku, Railway, AWS)
- Microservices

WAR for:
- Legacy infrastructure
- Existing application servers

2. Spring Profiles​

Define Profiles​

src/main/resources/
├── application.properties # Common configuration
├── application-dev.properties # Development
├── application-prod.properties # Production
└── application-test.properties # Tests

application.properties (common)​

spring.application.name=myapp
server.port=8080

# Default profile
spring.profiles.active=dev

application-dev.properties​

# In-memory H2 database
spring.datasource.url=jdbc:h2:mem:devdb
spring.datasource.driver-class-name=org.h2.Driver
spring.h2.console.enabled=true

# JPA
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true

# Verbose logging
logging.level.com.myapp=DEBUG
logging.level.org.hibernate.SQL=DEBUG

# Actuator: expose everything in dev
management.endpoints.web.exposure.include=*

application-prod.properties​

# PostgreSQL in production
spring.datasource.url=${DATABASE_URL}
spring.datasource.username=${DB_USERNAME}
spring.datasource.password=${DB_PASSWORD}

# JPA
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.show-sql=false

# Minimal logging
logging.level.root=WARN
logging.level.com.myapp=INFO

# Actuator: secured
management.endpoints.web.exposure.include=health,info,prometheus
management.endpoint.health.show-details=when_authorized

# Security
server.error.include-stacktrace=never

Activate a Profile​

# Via JVM argument
java -jar myapp.jar --spring.profiles.active=prod

# Via environment variable
export SPRING_PROFILES_ACTIVE=prod
java -jar myapp.jar

# Via Docker
docker run -e SPRING_PROFILES_ACTIVE=prod myapp

3. Externalized Configuration​

Order of Priority​

Spring Boot loads configuration in this order (increasing priority):

1. application.properties (inside JAR)
2. application-{profile}.properties (inside JAR)
3. application.properties (outside JAR)
4. application-{profile}.properties (outside JAR)
5. Environment variables
6. Command line arguments

Environment Variables​

# application.properties
spring.datasource.url=${DATABASE_URL:jdbc:h2:mem:default}
spring.datasource.username=${DB_USER:sa}
spring.datasource.password=${DB_PASS:}
# Set variables
export DATABASE_URL=jdbc:postgresql://localhost:5432/mydb
export DB_USER=myuser
export DB_PASS=secret

java -jar myapp.jar

YAML Configuration (alternative)​

# application.yml
spring:
application:
name: myapp
profiles:
active: dev

---
spring:
config:
activate:
on-profile: dev
datasource:
url: jdbc:h2:mem:devdb
h2:
console:
enabled: true

---
spring:
config:
activate:
on-profile: prod
datasource:
url: ${DATABASE_URL}
username: ${DB_USERNAME}
password: ${DB_PASSWORD}

4. Secrets Management​

❌ Never Do​

# NEVER in source code!
spring.datasource.password=MySecretPassword123
api.key=sk-1234567890abcdef

✅ Best Practices​

Option 1: Environment Variables​

export DB_PASSWORD=secret
export API_KEY=sk-xxx

Option 2: .env File (local only)​

# .env (add to .gitignore!)
DATABASE_URL=jdbc:postgresql://localhost:5432/mydb
DB_PASSWORD=secret
API_KEY=sk-xxx

Option 3: Secrets Managers​

# Kubernetes Secret
apiVersion: v1
kind: Secret
metadata:
name: myapp-secrets
type: Opaque
data:
db-password: c2VjcmV0 # base64

Option 4: Spring Cloud Config​

# For centralized secrets
spring:
cloud:
config:
uri: http://config-server:8888

.gitignore​

# Secrets
.env
*.pem
*.key
application-local.properties
secrets/

5. Production Optimizations​

JVM Configuration​

# Production JVM settings
java -Xms512m -Xmx1024m \
-XX:+UseG1GC \
-XX:MaxGCPauseMillis=200 \
-Djava.security.egd=file:/dev/./urandom \
-jar myapp.jar

application-prod.properties​

# Response compression
server.compression.enabled=true
server.compression.mime-types=application/json,text/html,text/css
server.compression.min-response-size=1024

# Optimized connection pool
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.idle-timeout=300000

# Template caching
spring.thymeleaf.cache=true

# Disable dev features
spring.devtools.restart.enabled=false
spring.h2.console.enabled=false

Graceful Shutdown​

# Wait for ongoing requests to finish
server.shutdown=graceful
spring.lifecycle.timeout-per-shutdown-phase=30s

6. Build for Production​

Maven​

# Build with prod profile
mvn clean package -Pprod -DskipTests

# Or with Spring profile
mvn clean package -Dspring.profiles.active=prod

pom.xml - Maven Profiles​

<profiles>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<spring.profiles.active>dev</spring.profiles.active>
</properties>
</profile>

<profile>
<id>prod</id>
<properties>
<spring.profiles.active>prod</spring.profiles.active>
</properties>
</profile>
</profiles>

<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>

Verify the JAR​

# JAR content
jar tf target/myapp-1.0.0.jar

# Test locally
java -jar target/myapp-1.0.0.jar --spring.profiles.active=prod

7. Summary​

Production Checklist​

□ Executable JAR created
□ Profiles configured (dev, prod, test)
□ Secrets externalized (not in code)
□ Environment variables documented
□ Logging configured (not DEBUG in prod)
□ Actuator secured
□ Compression enabled
□ Connection pool configured
□ Graceful shutdown enabled

Configuration Files​

application.properties        → Common configuration
application-dev.properties → H2, DEBUG, everything exposed
application-prod.properties → PostgreSQL, WARN, secured
application-test.properties → H2, for tests

Essential Variables​

SPRING_PROFILES_ACTIVE=prod
DATABASE_URL=jdbc:postgresql://...
DB_USERNAME=myuser
DB_PASSWORD=secret
SERVER_PORT=8080

🎯 Next Step​

The application is ready. Now, let's containerize it with Docker!

➡️ Chapter 2: Docker Containerization


⬅️ Back to Module 12