deployment.md 48.4 KB
Newer Older
茶陵後's avatar
茶陵後 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
# Deploying Spring Boot Applications

Spring Boot’s flexible packaging options provide a great deal of choice when it comes to deploying your application.
You can deploy Spring Boot applications to a variety of cloud platforms, to virtual/real machines, or make them fully executable for Unix systems.

This section covers some of the more common deployment scenarios.

## 1. Deploying to the Cloud

Spring Boot’s executable jars are ready-made for most popular cloud PaaS (Platform-as-a-Service) providers.
These providers tend to require that you “bring your own container”.
They manage application processes (not Java applications specifically), so they need an intermediary layer that adapts *your* application to the *cloud’s* notion of a running process.

Two popular cloud providers, Heroku and Cloud Foundry, employ a “buildpack” approach.
The buildpack wraps your deployed code in whatever is needed to *start* your application.
It might be a JDK and a call to `java`, an embedded web server, or a full-fledged application server.
A buildpack is pluggable, but ideally you should be able to get by with as few customizations to it as possible.
This reduces the footprint of functionality that is not under your control.
It minimizes divergence between development and production environments.

Ideally, your application, like a Spring Boot executable jar, has everything that it needs to run packaged within it.

In this section, we look at what it takes to get the [application that we developed](getting-started.html#getting-started.first-application) in the “Getting Started” section up and running in the Cloud.

### 1.1. Cloud Foundry

Cloud Foundry provides default buildpacks that come into play if no other buildpack is specified.
The Cloud Foundry [Java buildpack](https://github.com/cloudfoundry/java-buildpack) has excellent support for Spring applications, including Spring Boot.
You can deploy stand-alone executable jar applications as well as traditional `.war` packaged applications.

Once you have built your application (by using, for example, `mvn clean package`) and have [installed the `cf` command line tool](https://docs.cloudfoundry.org/cf-cli/install-go-cli.html), deploy your application by using the `cf push` command, substituting the path to your compiled `.jar`.
Be sure to have [logged in with your `cf` command line client](https://docs.cloudfoundry.org/cf-cli/getting-started.html#login) before pushing an application.
The following line shows using the `cf push` command to deploy an application:

```
$ cf push acloudyspringtime -p target/demo-0.0.1-SNAPSHOT.jar
```

|   |In the preceding example, we substitute `acloudyspringtime` for whatever value you give `cf` as the name of your application.|
|---|-----------------------------------------------------------------------------------------------------------------------------|

See the [`cf push` documentation](https://docs.cloudfoundry.org/cf-cli/getting-started.html#push) for more options.
If there is a Cloud Foundry [`manifest.yml`](https://docs.cloudfoundry.org/devguide/deploy-apps/manifest.html) file present in the same directory, it is considered.

At this point, `cf` starts uploading your application, producing output similar to the following example:

```
Uploading acloudyspringtime... OK
Preparing to start acloudyspringtime... OK
-----> Downloaded app package (8.9M)
-----> Java Buildpack Version: v3.12 (offline) | https://github.com/cloudfoundry/java-buildpack.git#6f25b7e
-----> Downloading Open Jdk JRE 1.8.0_121 from https://java-buildpack.cloudfoundry.org/openjdk/trusty/x86_64/openjdk-1.8.0_121.tar.gz (found in cache)
       Expanding Open Jdk JRE to .java-buildpack/open_jdk_jre (1.6s)
-----> Downloading Open JDK Like Memory Calculator 2.0.2_RELEASE from https://java-buildpack.cloudfoundry.org/memory-calculator/trusty/x86_64/memory-calculator-2.0.2_RELEASE.tar.gz (found in cache)
       Memory Settings: -Xss349K -Xmx681574K -XX:MaxMetaspaceSize=104857K -Xms681574K -XX:MetaspaceSize=104857K
-----> Downloading Container Certificate Trust Store 1.0.0_RELEASE from https://java-buildpack.cloudfoundry.org/container-certificate-trust-store/container-certificate-trust-store-1.0.0_RELEASE.jar (found in cache)
       Adding certificates to .java-buildpack/container_certificate_trust_store/truststore.jks (0.6s)
-----> Downloading Spring Auto Reconfiguration 1.10.0_RELEASE from https://java-buildpack.cloudfoundry.org/auto-reconfiguration/auto-reconfiguration-1.10.0_RELEASE.jar (found in cache)
Checking status of app 'acloudyspringtime'...
  0 of 1 instances running (1 starting)
  ...
  0 of 1 instances running (1 starting)
  ...
  0 of 1 instances running (1 starting)
  ...
  1 of 1 instances running (1 running)

App started
```

Congratulations! The application is now live!

Once your application is live, you can verify the status of the deployed application by using the `cf apps` command, as shown in the following example:

```
$ cf apps
Getting applications in ...
OK

name                 requested state   instances   memory   disk   urls
...
acloudyspringtime    started           1/1         512M     1G     acloudyspringtime.cfapps.io
...
```

Once Cloud Foundry acknowledges that your application has been deployed, you should be able to find the application at the URI given.
In the preceding example, you could find it at `https://acloudyspringtime.cfapps.io/`.

#### 1.1.1. Binding to Services

By default, metadata about the running application as well as service connection information is exposed to the application as environment variables (for example: `$VCAP_SERVICES`).
This architecture decision is due to Cloud Foundry’s polyglot (any language and platform can be supported as a buildpack) nature.
Process-scoped environment variables are language agnostic.

Environment variables do not always make for the easiest API, so Spring Boot automatically extracts them and flattens the data into properties that can be accessed through Spring’s `Environment` abstraction, as shown in the following example:

```
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class MyBean implements EnvironmentAware {

    private String instanceId;

    @Override
    public void setEnvironment(Environment environment) {
        this.instanceId = environment.getProperty("vcap.application.instance_id");
    }

    // ...

}

```

All Cloud Foundry properties are prefixed with `vcap`.
You can use `vcap` properties to access application information (such as the public URL of the application) and service information (such as database credentials).
See the [‘CloudFoundryVcapEnvironmentPostProcessor’](https://docs.spring.io/spring-boot/docs/2.6.4/api/org/springframework/boot/cloud/CloudFoundryVcapEnvironmentPostProcessor.html) Javadoc for complete details.

|   |The [Java CFEnv](https://github.com/pivotal-cf/java-cfenv/) project is a better fit for tasks such as configuring a DataSource.|
|---|-------------------------------------------------------------------------------------------------------------------------------|

### 1.2. Kubernetes

Spring Boot auto-detects Kubernetes deployment environments by checking the environment for `"*_SERVICE_HOST"` and `"*_SERVICE_PORT"` variables.
You can override this detection with the `spring.main.cloud-platform` configuration property.

Spring Boot helps you to [manage the state of your application](features.html#features.spring-application.application-availability) and export it with [HTTP Kubernetes Probes using Actuator](actuator.html#actuator.endpoints.kubernetes-probes).

#### 1.2.1. Kubernetes Container Lifecycle

When Kubernetes deletes an application instance, the shutdown process involves several subsystems concurrently: shutdown hooks, unregistering the service, removing the instance from the load-balancer…​
Because this shutdown processing happens in parallel (and due to the nature of distributed systems), there is a window during which traffic can be routed to a pod that has also begun its shutdown processing.

You can configure a sleep execution in a preStop handler to avoid requests being routed to a pod that has already begun shutting down.
This sleep should be long enough for new requests to stop being routed to the pod and its duration will vary from deployment to deployment.
The preStop handler can be configured by using the PodSpec in the pod’s configuration file as follows:

```
spec:
  containers:
  - name: "example-container"
    image: "example-image"
    lifecycle:
      preStop:
        exec:
          command: ["sh", "-c", "sleep 10"]
```

Once the pre-stop hook has completed, SIGTERM will be sent to the container and [graceful shutdown](web.html#web.graceful-shutdown) will begin, allowing any remaining in-flight requests to complete.

|   |When Kubernetes sends a SIGTERM signal to the pod, it waits for a specified time called the termination grace period (the default for which is 30 seconds).<br/>If the containers are still running after the grace period, they are sent the SIGKILL signal and forcibly removed.<br/>If the pod takes longer than 30 seconds to shut down, which could be because you have increased `spring.lifecycle.timeout-per-shutdown-phase`, make sure to increase the termination grace period by setting the `terminationGracePeriodSeconds` option in the Pod YAML.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### 1.3. Heroku

Heroku is another popular PaaS platform.
To customize Heroku builds, you provide a `Procfile`, which provides the incantation required to deploy an application.
Heroku assigns a `port` for the Java application to use and then ensures that routing to the external URI works.

You must configure your application to listen on the correct port.
The following example shows the `Procfile` for our starter REST application:

```
web: java -Dserver.port=$PORT -jar target/demo-0.0.1-SNAPSHOT.jar
```

Spring Boot makes `-D` arguments available as properties accessible from a Spring `Environment` instance.
The `server.port` configuration property is fed to the embedded Tomcat, Jetty, or Undertow instance, which then uses the port when it starts up.
The `$PORT` environment variable is assigned to us by the Heroku PaaS.

This should be everything you need.
The most common deployment workflow for Heroku deployments is to `git push` the code to production, as shown in the following example:

```
$ git push heroku main
```

Which will result in the following:

```
Initializing repository, done.
Counting objects: 95, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (78/78), done.
Writing objects: 100% (95/95), 8.66 MiB | 606.00 KiB/s, done.
Total 95 (delta 31), reused 0 (delta 0)

-----> Java app detected
-----> Installing OpenJDK 1.8... done
-----> Installing Maven 3.3.1... done
-----> Installing settings.xml... done
-----> Executing: mvn -B -DskipTests=true clean install

       [INFO] Scanning for projects...
       Downloading: https://repo.spring.io/...
       Downloaded: https://repo.spring.io/... (818 B at 1.8 KB/sec)
        ....
       Downloaded: https://s3pository.heroku.com/jvm/... (152 KB at 595.3 KB/sec)
       [INFO] Installing /tmp/build_0c35a5d2-a067-4abc-a232-14b1fb7a8229/target/...
       [INFO] Installing /tmp/build_0c35a5d2-a067-4abc-a232-14b1fb7a8229/pom.xml ...
       [INFO] ------------------------------------------------------------------------
       [INFO] BUILD SUCCESS
       [INFO] ------------------------------------------------------------------------
       [INFO] Total time: 59.358s
       [INFO] Finished at: Fri Mar 07 07:28:25 UTC 2014
       [INFO] Final Memory: 20M/493M
       [INFO] ------------------------------------------------------------------------

-----> Discovering process types
       Procfile declares types -> web

-----> Compressing... done, 70.4MB
-----> Launching... done, v6
       https://agile-sierra-1405.herokuapp.com/ deployed to Heroku

To [email protected]:agile-sierra-1405.git
 * [new branch]      main -> main
```

Your application should now be up and running on Heroku.
For more details, see [Deploying Spring Boot Applications to Heroku](https://devcenter.heroku.com/articles/deploying-spring-boot-apps-to-heroku).

### 1.4. OpenShift

[OpenShift](https://www.openshift.com/) has many resources describing how to deploy Spring Boot applications, including:

* [Using the S2I builder](https://blog.openshift.com/using-openshift-enterprise-grade-spring-boot-deployments/)

* [Architecture guide](https://access.redhat.com/documentation/en-us/reference_architectures/2017/html-single/spring_boot_microservices_on_red_hat_openshift_container_platform_3/)

* [Running as a traditional web application on Wildfly](https://blog.openshift.com/using-spring-boot-on-openshift/)

* [OpenShift Commons Briefing](https://blog.openshift.com/openshift-commons-briefing-96-cloud-native-applications-spring-rhoar/)

### 1.5. Amazon Web Services (AWS)

Amazon Web Services offers multiple ways to install Spring Boot-based applications, either as traditional web applications (war) or as executable jar files with an embedded web server.
The options include:

* AWS Elastic Beanstalk

* AWS Code Deploy

* AWS OPS Works

* AWS Cloud Formation

* AWS Container Registry

Each has different features and pricing models.
In this document, we describe to approach using AWS Elastic Beanstalk.

#### 1.5.1. AWS Elastic Beanstalk

As described in the official [Elastic Beanstalk Java guide](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_Java.html), there are two main options to deploy a Java application.
You can either use the “Tomcat Platform” or the “Java SE platform”.

##### Using the Tomcat Platform

This option applies to Spring Boot projects that produce a war file.
No special configuration is required.
You need only follow the official guide.

##### Using the Java SE Platform

This option applies to Spring Boot projects that produce a jar file and run an embedded web container.
Elastic Beanstalk environments run an nginx instance on port 80 to proxy the actual application, running on port 5000.
To configure it, add the following line to your `application.properties` file:

```
server.port=5000
```

|   |Upload binaries instead of sources<br/><br/>By default, Elastic Beanstalk uploads sources and compiles them in AWS.<br/>However, it is best to upload the binaries instead.<br/>To do so, add lines similar to the following to your `.elasticbeanstalk/config.yml` file:<br/><br/>```<br/>deploy:<br/>    artifact: target/demo-0.0.1-SNAPSHOT.jar<br/>```|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|   |Reduce costs by setting the environment type<br/><br/>By default an Elastic Beanstalk environment is load balanced.<br/>The load balancer has a significant cost.<br/>To avoid that cost, set the environment type to “Single instance”, as described in [the Amazon documentation](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environments-create-wizard.html#environments-create-wizard-capacity).<br/>You can also create single instance environments by using the CLI and the following command:<br/><br/>```<br/>eb create -s<br/>```|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### 1.5.2. Summary

This is one of the easiest ways to get to AWS, but there are more things to cover, such as how to integrate Elastic Beanstalk into any CI / CD tool, use the Elastic Beanstalk Maven plugin instead of the CLI, and others.
There is a [blog post](https://exampledriven.wordpress.com/2017/01/09/spring-boot-aws-elastic-beanstalk-example/) covering these topics more in detail.

### 1.6. CloudCaptain and Amazon Web Services

[CloudCaptain](https://cloudcaptain.sh/) works by turning your Spring Boot executable jar or war into a minimal VM image that can be deployed unchanged either on VirtualBox or on AWS.
CloudCaptain comes with deep integration for Spring Boot and uses the information from your Spring Boot configuration file to automatically configure ports and health check URLs.
CloudCaptain leverages this information both for the images it produces as well as for all the resources it provisions (instances, security groups, elastic load balancers, and so on).

Once you have created a [CloudCaptain account](https://console.cloudcaptain.sh), connected it to your AWS account, installed the latest version of the CloudCaptain Client, and ensured that the application has been built by Maven or Gradle (by using, for example, `mvn clean package`), you can deploy your Spring Boot application to AWS with a command similar to the following:

```
$ boxfuse run myapp-1.0.jar -env=prod
```

See the [`boxfuse run` documentation](https://cloudcaptain.sh/docs/commandline/run.html) for more options.
If there is a [`boxfuse.conf`](https://cloudcaptain.sh/docs/commandline/#configuration) file present in the current directory, it is considered.

|   |By default, CloudCaptain activates a Spring profile named `boxfuse` on startup.<br/>If your executable jar or war contains an [`application-boxfuse.properties`](https://cloudcaptain.sh/docs/payloads/springboot.html#configuration) file, CloudCaptain bases its configuration on the properties it contains.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

At this point, CloudCaptain creates an image for your application, uploads it, and configures and starts the necessary resources on AWS, resulting in output similar to the following example:

```
Fusing Image for myapp-1.0.jar ...
Image fused in 00:06.838s (53937 K) -> axelfontaine/myapp:1.0
Creating axelfontaine/myapp ...
Pushing axelfontaine/myapp:1.0 ...
Verifying axelfontaine/myapp:1.0 ...
Creating Elastic IP ...
Mapping myapp-axelfontaine.boxfuse.io to 52.28.233.167 ...
Waiting for AWS to create an AMI for axelfontaine/myapp:1.0 in eu-central-1 (this may take up to 50 seconds) ...
AMI created in 00:23.557s -> ami-d23f38cf
Creating security group boxfuse-sg_axelfontaine/myapp:1.0 ...
Launching t2.micro instance of axelfontaine/myapp:1.0 (ami-d23f38cf) in eu-central-1 ...
Instance launched in 00:30.306s -> i-92ef9f53
Waiting for AWS to boot Instance i-92ef9f53 and Payload to start at https://52.28.235.61/ ...
Payload started in 00:29.266s -> https://52.28.235.61/
Remapping Elastic IP 52.28.233.167 to i-92ef9f53 ...
Waiting 15s for AWS to complete Elastic IP Zero Downtime transition ...
Deployment completed successfully. axelfontaine/myapp:1.0 is up and running at https://myapp-axelfontaine.boxfuse.io/
```

Your application should now be up and running on AWS.

See the blog post on [deploying Spring Boot apps on EC2](https://cloudcaptain.sh/blog/spring-boot-ec2.html) as well as the [documentation for the CloudCaptain Spring Boot integration](https://cloudcaptain.sh/docs/payloads/springboot.html) to get started with a Maven build to run the app.

### 1.7. Azure

This [Getting Started guide](https://spring.io/guides/gs/spring-boot-for-azure/) walks you through deploying your Spring Boot application to either [Azure Spring Cloud](https://azure.microsoft.com/en-us/services/spring-cloud/) or [Azure App Service](https://docs.microsoft.com/en-us/azure/app-service/overview).

### 1.8. Google Cloud

Google Cloud has several options that can be used to launch Spring Boot applications.
The easiest to get started with is probably App Engine, but you could also find ways to run Spring Boot in a container with Container Engine or on a virtual machine with Compute Engine.

To run in App Engine, you can create a project in the UI first, which sets up a unique identifier for you and also sets up HTTP routes.
Add a Java app to the project and leave it empty and then use the [Google Cloud SDK](https://cloud.google.com/sdk/install) to push your Spring Boot app into that slot from the command line or CI build.

App Engine Standard requires you to use WAR packaging.
Follow [these steps](https://github.com/GoogleCloudPlatform/java-docs-samples/tree/master/appengine-java8/springboot-helloworld/README.md) to deploy App Engine Standard application to Google Cloud.

Alternatively, App Engine Flex requires you to create an `app.yaml` file to describe the resources your app requires.
Normally, you put this file in `src/main/appengine`, and it should resemble the following file:

```
service: "default"

runtime: "java"
env: "flex"

runtime_config:
  jdk: "openjdk8"

handlers:
- url: "/.*"
  script: "this field is required, but ignored"

manual_scaling:
  instances: 1

health_check:
  enable_health_check: false

env_variables:
  ENCRYPT_KEY: "your_encryption_key_here"
```

You can deploy the app (for example, with a Maven plugin) by adding the project ID to the build configuration, as shown in the following example:

```
<plugin>
    <groupId>com.google.cloud.tools</groupId>
    <artifactId>appengine-maven-plugin</artifactId>
    <version>1.3.0</version>
    <configuration>
        <project>myproject</project>
    </configuration>
</plugin>
```

Then deploy with `mvn appengine:deploy` (if you need to authenticate first, the build fails).

## 2. Installing Spring Boot Applications

In addition to running Spring Boot applications by using `java -jar`, it is also possible to make fully executable applications for Unix systems.
A fully executable jar can be executed like any other executable binary or it can be [registered with `init.d` or `systemd`](#deployment.installing.nix-services).
This helps when installing and managing Spring Boot applications in common production environments.

|   |Fully executable jars work by embedding an extra script at the front of the file.<br/>Currently, some tools do not accept this format, so you may not always be able to use this technique.<br/>For example, `jar -xf` may silently fail to extract a jar or war that has been made fully executable.<br/>It is recommended that you make your jar or war fully executable only if you intend to execute it directly, rather than running it with `java -jar` or deploying it to a servlet container.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|   |A zip64-format jar file cannot be made fully executable.<br/>Attempting to do so will result in a jar file that is reported as corrupt when executed directly or with `java -jar`.<br/>A standard-format jar file that contains one or more zip64-format nested jars can be fully executable.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

To create a ‘fully executable’ jar with Maven, use the following plugin configuration:

```
<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <executable>true</executable>
    </configuration>
</plugin>
```

The following example shows the equivalent Gradle configuration:

```
bootJar {
    launchScript()
}
```

You can then run your application by typing `./my-application.jar` (where `my-application` is the name of your artifact).
The directory containing the jar is used as your application’s working directory.

### 2.1. Supported Operating Systems

The default script supports most Linux distributions and is tested on CentOS and Ubuntu.
Other platforms, such as OS X and FreeBSD, require the use of a custom `embeddedLaunchScript`.

### 2.2. Unix/Linux Services

Spring Boot application can be easily started as Unix/Linux services by using either `init.d` or `systemd`.

#### 2.2.1. Installation as an init.d Service (System V)

If you configured Spring Boot’s Maven or Gradle plugin to generate a [fully executable jar](#deployment.installing), and you do not use a custom `embeddedLaunchScript`, your application can be used as an `init.d` service.
To do so, symlink the jar to `init.d` to support the standard `start`, `stop`, `restart`, and `status` commands.

The script supports the following features:

* Starts the services as the user that owns the jar file

* Tracks the application’s PID by using `/var/run/<appname>/<appname>.pid`

* Writes console logs to `/var/log/<appname>.log`

Assuming that you have a Spring Boot application installed in `/var/myapp`, to install a Spring Boot application as an `init.d` service, create a symlink, as follows:

```
$ sudo ln -s /var/myapp/myapp.jar /etc/init.d/myapp
```

Once installed, you can start and stop the service in the usual way.
For example, on a Debian-based system, you could start it with the following command:

```
$ service myapp start
```

|   |If your application fails to start, check the log file written to `/var/log/<appname>.log` for errors.|
|---|------------------------------------------------------------------------------------------------------|

You can also flag the application to start automatically by using your standard operating system tools.
For example, on Debian, you could use the following command:

```
$ update-rc.d myapp defaults <priority>
```

##### Securing an init.d Service

|   |The following is a set of guidelines on how to secure a Spring Boot application that runs as an init.d service.<br/>It is not intended to be an exhaustive list of everything that should be done to harden an application and the environment in which it runs.|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

When executed as root, as is the case when root is being used to start an init.d service, the default executable script runs the application as the user specified in the `RUN_AS_USER` environment variable.
When the environment variable is not set, the user who owns the jar file is used instead.
You should never run a Spring Boot application as `root`, so `RUN_AS_USER` should never be root and your application’s jar file should never be owned by root.
Instead, create a specific user to run your application and set the `RUN_AS_USER` environment variable or use `chown` to make it the owner of the jar file, as shown in the following example:

```
$ chown bootapp:bootapp your-app.jar
```

In this case, the default executable script runs the application as the `bootapp` user.

|   |To reduce the chances of the application’s user account being compromised, you should consider preventing it from using a login shell.<br/>For example, you can set the account’s shell to `/usr/sbin/nologin`.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

You should also take steps to prevent the modification of your application’s jar file.
Firstly, configure its permissions so that it cannot be written and can only be read or executed by its owner, as shown in the following example:

```
$ chmod 500 your-app.jar
```

Second, you should also take steps to limit the damage if your application or the account that is running it is compromised.
If an attacker does gain access, they could make the jar file writable and change its contents.
One way to protect against this is to make it immutable by using `chattr`, as shown in the following example:

```
$ sudo chattr +i your-app.jar
```

This will prevent any user, including root, from modifying the jar.

If root is used to control the application’s service and you [use a `.conf` file](#deployment.installing.nix-services.script-customization.when-running.conf-file) to customize its startup, the `.conf` file is read and evaluated by the root user.
It should be secured accordingly.
Use `chmod` so that the file can only be read by the owner and use `chown` to make root the owner, as shown in the following example:

```
$ chmod 400 your-app.conf
$ sudo chown root:root your-app.conf
```

#### 2.2.2. Installation as a systemd Service

`systemd` is the successor of the System V init system and is now being used by many modern Linux distributions.
Although you can continue to use `init.d` scripts with `systemd`, it is also possible to launch Spring Boot applications by using `systemd` ‘service’ scripts.

Assuming that you have a Spring Boot application installed in `/var/myapp`, to install a Spring Boot application as a `systemd` service, create a script named `myapp.service` and place it in `/etc/systemd/system` directory.
The following script offers an example:

```
[Unit]
Description=myapp
After=syslog.target

[Service]
User=myapp
ExecStart=/var/myapp/myapp.jar
SuccessExitStatus=143

[Install]
WantedBy=multi-user.target
```

|   |Remember to change the `Description`, `User`, and `ExecStart` fields for your application.|
|---|------------------------------------------------------------------------------------------|

|   |The `ExecStart` field does not declare the script action command, which means that the `run` command is used by default.|
|---|------------------------------------------------------------------------------------------------------------------------|

Note that, unlike when running as an `init.d` service, the user that runs the application, the PID file, and the console log file are managed by `systemd` itself and therefore must be configured by using appropriate fields in the ‘service’ script.
Consult the [service unit configuration man page](https://www.freedesktop.org/software/systemd/man/systemd.service.html) for more details.

To flag the application to start automatically on system boot, use the following command:

```
$ systemctl enable myapp.service
```

Run `man systemctl` for more details.

#### 2.2.3. Customizing the Startup Script

The default embedded startup script written by the Maven or Gradle plugin can be customized in a number of ways.
For most people, using the default script along with a few customizations is usually enough.
If you find you cannot customize something that you need to, use the `embeddedLaunchScript` option to write your own file entirely.

##### Customizing the Start Script When It Is Written #####

It often makes sense to customize elements of the start script as it is written into the jar file.
For example, init.d scripts can provide a “description”.
Since you know the description up front (and it need not change), you may as well provide it when the jar is generated.

To customize written elements, use the `embeddedLaunchScriptProperties` option of the Spring Boot Maven plugin or the [`properties` property of the Spring Boot Gradle plugin’s `launchScript`](https://docs.spring.io/spring-boot/docs/2.6.4/gradle-plugin/reference/htmlsingle/#packaging-executable-configuring-launch-script).

The following property substitutions are supported with the default script:

|           Name           |                                                                                            Description                                                                                            |                                   Gradle default                                   |                       Maven default                        |
|--------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------|------------------------------------------------------------|
|          `mode`          |                                                                                         The script mode.                                                                                          |                                       `auto`                                       |                           `auto`                           |
|    `initInfoProvides`    |                                                                               The `Provides` section of “INIT INFO”                                                                               |                                 `${task.baseName}`                                 |                  `${project.artifactId}`                   |
| `initInfoRequiredStart`  |                                                                             `Required-Start` section of “INIT INFO”.                                                                              |                           `$remote_fs $syslog $network`                            |               `$remote_fs $syslog $network`                |
|  `initInfoRequiredStop`  |                                                                              `Required-Stop` section of “INIT INFO”.                                                                              |                           `$remote_fs $syslog $network`                            |               `$remote_fs $syslog $network`                |
|  `initInfoDefaultStart`  |                                                                              `Default-Start` section of “INIT INFO”.                                                                              |                                     `2 3 4 5`                                      |                         `2 3 4 5`                          |
|  `initInfoDefaultStop`   |                                                                              `Default-Stop` section of “INIT INFO”.                                                                               |                                      `0 1 6`                                       |                          `0 1 6`                           |
|`initInfoShortDescription`|                                                                            `Short-Description` section of “INIT INFO”.                                                                            |Single-line version of `${project.description}` (falling back to `${task.baseName}`)|                     `${project.name}`                      |
|  `initInfoDescription`   |                                                                               `Description` section of “INIT INFO”.                                                                               |           `${project.description}` (falling back to `${task.baseName}`)            |`${project.description}` (falling back to `${project.name}`)|
|   `initInfoChkconfig`    |                                                                                `chkconfig` section of “INIT INFO”                                                                                 |                                    `2345 99 01`                                    |                        `2345 99 01`                        |
|       `confFolder`       |                                                                                The default value for `CONF_FOLDER`                                                                                |                             Folder containing the jar                              |                 Folder containing the jar                  |
|   `inlinedConfScript`    |Reference to a file script that should be inlined in the default launch script.<br/>This can be used to set environmental variables such as `JAVA_OPTS` before any external config files are loaded|                                                                                    |                                                            |
|       `logFolder`        |                                                              Default value for `LOG_FOLDER`.<br/>Only valid for an `init.d` service                                                               |                                                                                    |                                                            |
|      `logFilename`       |                                                             Default value for `LOG_FILENAME`.<br/>Only valid for an `init.d` service                                                              |                                                                                    |                                                            |
|       `pidFolder`        |                                                              Default value for `PID_FOLDER`.<br/>Only valid for an `init.d` service                                                               |                                                                                    |                                                            |
|      `pidFilename`       |                                                Default value for the name of the PID file in `PID_FOLDER`.<br/>Only valid for an `init.d` service                                                 |                                                                                    |                                                            |
|   `useStartStopDaemon`   |                                               Whether the `start-stop-daemon` command, when it is available, should be used to control the process                                                |                                       `true`                                       |                           `true`                           |
|      `stopWaitTime`      |                                                       Default value for `STOP_WAIT_TIME` in seconds.<br/>Only valid for an `init.d` service                                                       |                                         60                                         |                             60                             |

##### Customizing a Script When It Runs #####

For items of the script that need to be customized *after* the jar has been written, you can use environment variables or a [config file](#deployment.installing.nix-services.script-customization.when-running.conf-file).

The following environment properties are supported with the default script:

|       Variable        |                                                                                                                                                                                    Description                                                                                                                                                                                     |
|-----------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|        `MODE`         |The “mode” of operation.<br/>The default depends on the way the jar was built but is usually `auto` (meaning it tries to guess if it is an init script by checking if it is a symlink in a directory called `init.d`).<br/>You can explicitly set it to `service` so that the `stop|start|status|restart` commands work or to `run` if you want to run the script in the foreground.|
|     `RUN_AS_USER`     |                                                                                                                                 The user that will be used to run the application.<br/>When not set, the user that owns the jar file will be used.                                                                                                                                 |
|`USE_START_STOP_DAEMON`|                                                                                                                           Whether the `start-stop-daemon` command, when it is available, should be used to control the process.<br/>Defaults to `true`.                                                                                                                            |
|     `PID_FOLDER`      |                                                                                                                                                              The root name of the pid folder (`/var/run` by default).                                                                                                                                                              |
|     `LOG_FOLDER`      |                                                                                                                                                     The name of the folder in which to put log files (`/var/log` by default).                                                                                                                                                      |
|     `CONF_FOLDER`     |                                                                                                                                            The name of the folder from which to read .conf files (same folder as jar-file by default).                                                                                                                                             |
|    `LOG_FILENAME`     |                                                                                                                                                     The name of the log file in the `LOG_FOLDER` (`<appname>.log` by default).                                                                                                                                                     |
|      `APP_NAME`       |                                                                                               The name of the app.<br/>If the jar is run from a symlink, the script guesses the app name.<br/>If it is not a symlink or you want to explicitly set the app name, this can be useful.                                                                                               |
|      `RUN_ARGS`       |                                                                                                                                                            The arguments to pass to the program (the Spring Boot app).                                                                                                                                                             |
|      `JAVA_HOME`      |                                                                                                     The location of the `java` executable is discovered by using the `PATH` by default, but you can set it explicitly if there is an executable file at `$JAVA_HOME/bin/java`.                                                                                                     |
|      `JAVA_OPTS`      |                                                                                                                                                              Options that are passed to the JVM when it is launched.                                                                                                                                                               |
|       `JARFILE`       |                                                                                                                             The explicit location of the jar file, in case the script is being used to launch a jar that it is not actually embedded.                                                                                                                              |
|        `DEBUG`        |                                                                                                                                        If not empty, sets the `-x` flag on the shell process, allowing you to see the logic in the script.                                                                                                                                         |
|   `STOP_WAIT_TIME`    |                                                                                                                                       The time in seconds to wait when stopping the application before forcing a shutdown (`60` by default).                                                                                                                                       |

|   |The `PID_FOLDER`, `LOG_FOLDER`, and `LOG_FILENAME` variables are only valid for an `init.d` service.<br/>For `systemd`, the equivalent customizations are made by using the ‘service’ script.<br/>See the [service unit configuration man page](https://www.freedesktop.org/software/systemd/man/systemd.service.html) for more details.|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

With the exception of `JARFILE` and `APP_NAME`, the settings listed in the preceding section can be configured by using a `.conf` file.
The file is expected to be next to the jar file and have the same name but suffixed with `.conf` rather than `.jar`.
For example, a jar named `/var/myapp/myapp.jar` uses the configuration file named `/var/myapp/myapp.conf`, as shown in the following example:

myapp.conf

```
JAVA_OPTS=-Xmx1024M
LOG_FOLDER=/custom/log/folder
```

|   |If you do not like having the config file next to the jar file, you can set a `CONF_FOLDER` environment variable to customize the location of the config file.|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------|

To learn about securing this file appropriately, see [the guidelines for securing an init.d service](#deployment.installing.nix-services.init-d.securing).

### 2.3. Microsoft Windows Services

A Spring Boot application can be started as a Windows service by using [`winsw`](https://github.com/kohsuke/winsw).

A ([separately maintained sample](https://github.com/snicoll/spring-boot-daemon)) describes step-by-step how you can create a Windows service for your Spring Boot application.

## 3. What to Read Next

See the [Cloud Foundry](https://www.cloudfoundry.org/), [Heroku](https://www.heroku.com/), [OpenShift](https://www.openshift.com), and [Boxfuse](https://boxfuse.com) web sites for more information about the kinds of features that a PaaS can offer.
These are just four of the most popular Java PaaS providers.
Since Spring Boot is so amenable to cloud-based deployment, you can freely consider other providers as well.

The next section goes on to cover the *[Spring Boot CLI](cli.html#cli)*, or you can jump ahead to read about *[build tool plugins](build-tool-plugins.html#build-tool-plugins)*.