How to Run Gatling Tests in Spring Boot with Environment Variables

July 26, 2026
Written By Digital Crafter Team

 

Performance testing becomes more useful when it reflects real deployment conditions. In a Spring Boot project, Gatling can be configured to run load tests against different environments without rewriting simulation code. By using environment variables, a development team can control the target URL, user load, test duration, authentication tokens, and other settings from the outside.

TLDR: Gatling tests in Spring Boot can be made flexible by reading configuration from environment variables. This allows the same simulation to run against local, staging, or production-like systems with different values. The usual setup involves adding Gatling dependencies, creating a simulation class, reading variables through Java or Scala APIs, and passing those variables through Maven, Gradle, Docker, or CI pipelines.

Why Use Environment Variables for Gatling Tests?

Gatling simulations often need values that change between environments. For example, a local test may target http://localhost:8080, while a staging test may target a hosted API gateway. Hardcoding these values makes the test suite difficult to maintain and risky to reuse.

Environment variables help separate test logic from runtime configuration. The simulation describes what users do, while external variables describe where and how the test runs. This approach is especially useful in Spring Boot projects because the application itself commonly uses environment-based configuration through profiles, properties, and deployment settings.

  • Portability: the same Gatling simulation can run locally, in Docker, or in CI/CD.
  • Security: sensitive values such as tokens do not need to be committed to source control.
  • Flexibility: load levels and durations can change without modifying code.
  • Consistency: teams can align performance test settings with Spring Boot deployment variables.

Adding Gatling to a Spring Boot Project

A Spring Boot application can run Gatling tests as part of the same repository. Many teams keep simulations under a dedicated test folder so the performance tests remain close to the application code but separate from unit and integration tests.

For Maven-based projects, the Gatling plugin and dependencies are commonly added to the pom.xml. The exact versions may vary, but the setup usually includes Gatling charts, the Gatling Maven plugin, and support for Java or Scala simulations.

<plugin>
  <groupId>io.gatling</groupId>
  <artifactId>gatling-maven-plugin</artifactId>
  <version>4.9.6</version>
</plugin>

With Gradle, a Gatling plugin can be configured in the build file. The key idea is the same: Gatling should be available as a test runner, while simulations should be placed in a predictable location such as src/test/gatling.

Creating a Gatling Simulation That Reads Environment Variables

A Gatling simulation can read environment variables directly from the JVM process. In Java, this is usually done with System.getenv(). In Scala, the equivalent is sys.env. The simulation can then fall back to defaults when variables are missing.

String baseUrl = System.getenv().getOrDefault(
  "BASE_URL",
  "http://localhost:8080"
);

int users = Integer.parseInt(
  System.getenv().getOrDefault("GATLING_USERS", "10")
);

int duration = Integer.parseInt(
  System.getenv().getOrDefault("GATLING_DURATION_SECONDS", "60")
);

This pattern keeps the simulation stable while allowing the runtime environment to define the behavior. A local developer can run a short, low-load test against a local Spring Boot instance. A CI pipeline can run a larger test against a staging deployment simply by providing different variables.

Example Simulation Structure

A basic simulation may define an HTTP protocol, a scenario, and an injection profile. The base URL, number of users, and test duration can all come from environment variables.

public class ApiSimulation extends Simulation {

  String baseUrl = System.getenv().getOrDefault(
    "BASE_URL",
    "http://localhost:8080"
  );

  int users = Integer.parseInt(
    System.getenv().getOrDefault("GATLING_USERS", "10")
  );

  int duration = Integer.parseInt(
    System.getenv().getOrDefault("GATLING_DURATION_SECONDS", "60")
  );

  HttpProtocolBuilder httpProtocol = http
    .baseUrl(baseUrl)
    .acceptHeader("application/json")
    .contentTypeHeader("application/json");

  ScenarioBuilder scenario = scenario("Spring Boot API Load Test")
    .exec(
      http("Get health endpoint")
        .get("/actuator/health")
        .check(status().is(200))
    );

  {
    setUp(
      scenario.injectOpen(
        rampUsers(users).during(duration)
      )
    ).protocols(httpProtocol);
  }
}

The health endpoint is a simple example, but the same structure can be expanded to test login flows, product searches, order creation, or any other application behavior. If authentication is required, a token can also be read from an environment variable and attached as a header.

String token = System.getenv().getOrDefault("API_TOKEN", "");

HttpProtocolBuilder httpProtocol = http
  .baseUrl(baseUrl)
  .authorizationHeader("Bearer " + token);

Running Against a Local Spring Boot Application

Before running Gatling, the Spring Boot application should be started. A developer may launch it through an IDE, Maven, Gradle, or a packaged jar. Once the application is listening on the expected port, environment variables can be supplied before the Gatling command.

export BASE_URL=http://localhost:8080
export GATLING_USERS=20
export GATLING_DURATION_SECONDS=90

mvn gatling:test

On Windows PowerShell, the syntax is different:

$env:BASE_URL="http://localhost:8080"
$env:GATLING_USERS="20"
$env:GATLING_DURATION_SECONDS="90"

mvn gatling:test

When the test finishes, Gatling generates an HTML report containing response times, request counts, error percentages, percentiles, and throughput metrics. These reports help the team identify slow endpoints, unstable behavior, and capacity limits.

Running Gatling with Spring Boot Profiles

Spring Boot profiles and Gatling environment variables can work together. For example, the application can start with a test profile while Gatling targets that instance using a matching base URL. The Spring Boot profile controls application configuration, while Gatling variables control test configuration.

SPRING_PROFILES_ACTIVE=test \
BASE_URL=http://localhost:8080 \
GATLING_USERS=50 \
mvn gatling:test

This separation is important. Spring Boot profiles should describe the application’s runtime behavior, such as database settings or external service mocks. Gatling variables should describe the performance test, such as traffic volume, duration, and target endpoints.

Using Environment Variables in Docker and CI/CD

In containerized environments, environment variables are usually passed through Docker commands, Docker Compose files, or orchestration platforms. This makes Gatling suitable for repeatable performance checks in automated pipelines.

docker run --rm \
  -e BASE_URL=https://staging.example.com \
  -e GATLING_USERS=100 \
  -e GATLING_DURATION_SECONDS=300 \
  performance-tests:latest

In CI/CD systems, variables can be stored as pipeline configuration or encrypted secrets. Non-sensitive values, such as user counts, may be visible in the pipeline file. Sensitive values, such as API tokens, should be stored in the platform’s secret management system.

Best Practices for Reliable Gatling Configuration

Environment variables are powerful, but they should be handled carefully. A simulation should validate critical values before the test begins. If a required token or target URL is missing, the test should fail early instead of producing misleading results.

  • Use clear variable names: names such as BASE_URL, GATLING_USERS, and API_TOKEN are easy to understand.
  • Provide safe defaults: defaults are useful for local testing, but production-like tests should use explicit values.
  • Avoid committing secrets: tokens, passwords, and private endpoints should come from secure environment storage.
  • Document required variables: the repository should include a short guide or example file.
  • Keep load realistic: user counts and durations should reflect actual business expectations.

It is also wise to separate smoke performance tests from heavy load tests. A small Gatling run can execute on every merge request, while larger tests can run nightly or before major releases. This prevents pipelines from becoming too slow while still giving the team regular performance feedback.

Common Mistakes to Avoid

One common mistake is testing a Spring Boot application before it is fully ready. If the application is still starting, Gatling may report failures that do not represent real performance problems. Health checks, startup waits, or pipeline readiness steps can reduce this issue.

Another mistake is using unrealistic data. If every virtual user requests the same account, product, or search term, the results may be distorted by caching or database hot spots. Parameterized feeders and varied request data help create more realistic tests.

Finally, teams should avoid treating Gatling reports as simple pass-or-fail artifacts. The real value comes from trend analysis. Response time percentiles, error rates, and throughput should be compared across builds so performance regressions become visible early.

FAQ

  • Can Gatling be used directly inside a Spring Boot project?
    Yes. Gatling simulations can live in the same repository as a Spring Boot application, usually under a dedicated test source directory.

  • How can Gatling read environment variables?
    Java simulations can use System.getenv(), while Scala simulations can use sys.env. Defaults can be added when variables are missing.

  • Should secrets be stored in Gatling code?
    No. API tokens, passwords, and private credentials should be passed through environment variables or secure CI/CD secret storage.

  • Can different environments use the same simulation?
    Yes. The same simulation can target local, staging, or production-like systems by changing variables such as BASE_URL and GATLING_USERS.

  • What should be measured in Gatling reports?
    Teams should review response time percentiles, request throughput, error rates, and trends across repeated test runs.