testcontainers/testcontainers-java · error · SQLException

Could not create new connection

Error message

Could not create new connection

What it means

createConnection(String) retries DriverManager.getConnection with a fresh JDBC URL until a retry limit; once exhausted it throws SQLException('Could not create new connection') with the last exception as cause. Unlike the wait-phase error, this happens on explicit connection creation after/during use.

Solutions

  1. Read the cause (lastException) to see the real failure (auth refused, unknown db, timeout)
  2. Verify username/password/database name match the container configuration
  3. Ensure the container is running and the mapped port is reachable from the test
  4. Check container logs for database-side errors

Example fix

// before
container.withUsername("wrong").withPassword("wrong");
// after
container.withUsername("test").withPassword("test").withDatabaseName("test");
Defensive patterns

Strategy: try-catch

Validate before calling

// verify reachability first
try (var probe = DriverManager.getConnection(container.getJdbcUrl(), container.getUsername(), container.getPassword())) { /* ok */ }

Try / catch

try { conn = container.createConnection("?"); } catch (SQLException e) { Throwable cause = e.getCause(); /* inspect cause: auth vs network vs DB error */ }

Prevention

When it happens

Trigger: All retry attempts of creating a Connection fail (network, auth, URL, or DB not accepting connections) within createConnection's retry loop.

Common situations: Wrong credentials in withUsername/withPassword; database stopped or crashed mid-test; connection URL parameters invalid; connection pool exhaustion or network policy blocking the mapped port.

Understand the failure class

Background: ECONNREFUSED and "connection refused" / "could not connect to server" errors: what they mean and how to fix them — this error's family across 44 libraries.

Related errors


AI-assisted analysis of testcontainers/testcontainers-java@8e549514e3 (2026-09-12). Data as JSON: /api/errors/59804ae5226dcc61. Report an issue: GitHub.

Appendix: source

Thrown at modules/jdbc/src/main/java/org/testcontainers/containers/JdbcDatabaseContainer.java:296

                try {
                    logger()
                        .debug(
                            "Trying to create JDBC connection using {} to {} with properties: {}",
                            jdbcDriverInstance.getClass().getName(),
                            url,
                            properties
                        );

                    return jdbcDriverInstance.connect(url, properties);
                } catch (SQLException e) {
                    lastException = e;
                    Thread.sleep(100L);
                }
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        throw new SQLException("Could not create new connection", lastException);
    }

    /**
     * Template method for constructing the JDBC URL to be used for creating {@link Connection}s.
     * This should be overridden if the JDBC URL and query string concatenation or URL string
     * construction needs to be different to normal.
     *
     * @param queryString query string parameters that should be appended to the JDBC connection URL.
     *                    The '?' character must be included
     * @return a full JDBC URL including queryString
     */
    protected String constructUrlForConnection(String queryString) {
        String baseUrl = getJdbcUrl();

        if ("".equals(queryString)) {
            return baseUrl;
        }

View on GitHub (pinned to 8e549514e3)