Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/env/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

### New Features

- The default ports `8888` (development) and `8889` (tests) now automatically fall back to the next available port when busy, so `wp-env start` works out of the box on hosts where those ports are taken; explicitly configured ports keep today's strict behavior unless `--auto-port` / `"autoPort": true` is passed, and the new `"autoPort": false` opt-out disables fallback even on the defaults. ([#49843](https://github.com/WordPress/gutenberg/issues/49843), [#74472](https://github.com/WordPress/gutenberg/pull/74472))

## 11.5.0 (2026-04-29)

## 11.4.0 (2026-04-15)
Expand Down
28 changes: 20 additions & 8 deletions packages/env/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ In this table, by default, you should see two entries: `wordpress` with port 888

### 2. Check the port number

By default `wp-env` uses port 8888, meaning that the local environment will be available at http://localhost:8888.
By default `wp-env` tries port 8888, meaning that the local environment will be available at http://localhost:8888. If 8888 is busy on your host and you have not configured a port explicitly, `wp-env` automatically falls back to the next available port and prints the resolved port at start time — see [Automatic Port Selection](#automatic-port-selection) for the full contract and how to opt out.

You can configure the port that `wp-env` uses so that it doesn't clash with another server by specifying the `WP_ENV_PORT` environment variable when starting `wp-env`:

Expand All @@ -149,7 +149,7 @@ $ WP_ENV_PORT=3333 wp-env start

Running `docker ps` and inspecting the `PORTS` column allows you to determine which port `wp-env` is currently using.

You may also specify the port numbers in your `.wp-env.json` file, but the environment variables will take precedence.
You may also specify the port numbers in your `.wp-env.json` file, but the environment variables will take precedence. Ports you set explicitly (in `.wp-env.json`, in `.wp-env.override.json`, or via `WP_ENV_PORT` / `WP_ENV_TESTS_PORT`) are never silently moved; if you need them to also auto-fall-back when busy, see the `--auto-port` flag in [Automatic Port Selection](#automatic-port-selection).

### 3. Restart `wp-env` with updates

Expand Down Expand Up @@ -365,8 +365,10 @@ Options:
[string]
--scripts Execute any configured lifecycle scripts.
[boolean] [default: true]
--auto-port Automatically find available ports when configured ports are
busy. [boolean]
--auto-port Also fall back to the next available port when explicitly
configured ports are busy. By default, only the standard ports
8888/8889 auto-fall-back. Overrides the .wp-env.json "autoPort"
setting. [boolean]
```

### `wp-env stop`
Expand Down Expand Up @@ -606,7 +608,7 @@ To enable editor autocomplete and validation, add a `$schema` key:
| `"port"` | `integer` | `8888` | The port number to use for the installation. |
| `"testsEnvironment"` | `boolean` | `false` | _Deprecated._ Whether to create a separate test environment with its own database and containers. Use `--config` with a separate config file instead. |
| `"testsPort"` | `integer` | `8889` | The port number for the test site. |
| `"autoPort"` | `boolean` | `false` | Whether to automatically find available HTTP ports when configured ports are busy. |
| `"autoPort"` | `boolean\|null`| `null` (defaults only) | Tri-state automatic HTTP port selection. When `null` (the default), the default ports `8888`/`8889` automatically fall back to the next available port if busy, but explicitly configured ports stay strict. Set to `true` to also fall back on user-set ports. Set to `false` to opt out entirely, including on the default ports. |
| `"config"` | `Object` | See below. | Mapping of wp-config.php constants to their desired values. |
| `"mappings"` | `Object` | `"{}"` | Mapping of WordPress directories to local directories to be mounted in the WordPress instance. |
| `"mysqlPort"` | `integer` | `null` (randomly assigned) | The MySQL port number to expose. |
Expand All @@ -619,15 +621,25 @@ _Note: the port number environment variable (`WP_ENV_PORT`) takes precedence ove

### Automatic Port Selection

By default, `wp-env` uses fixed ports (`8888` for development, `8889` for tests). If a port is busy, Docker will report an error at start time.
By default, `wp-env` tries the standard ports (`8888` for development, `8889` for tests). If you have not configured a port explicitly and one of those defaults is busy on the host, `wp-env` scans upward to the next available port (for example: `8888` → `8890` → `8891`, ...) and starts the environment there. The CLI prints a one-line notice through the same spinner used for other start-time messages so you can see which port was actually bound.

To opt in to automatic port selection, pass the `--auto-port` flag:
Ports that you configured yourself — through `port` / `testsPort` in `.wp-env.json`, in `.wp-env.override.json`, via `WP_ENV_PORT` / `WP_ENV_TESTS_PORT`, or any combination — are never silently moved. If your configured port is busy, the start fails with the existing port-conflict error so your explicit choice is honored.

If you want auto-fallback to apply to your configured ports too, pass the `--auto-port` flag (or set `"autoPort": true` in `.wp-env.json`):

```sh
wp-env start --auto-port
```

When `--auto-port` (or `"autoPort": true`) is enabled and a configured port is busy, `wp-env` scans upward from the configured port to find the next available one (for example: `8888`, `8889`, `8890`, ...). Automatic port selection is disabled when `CI` is set.
To opt out of the default-port fallback as well — for example, when you want a hard guarantee that `wp-env` only ever binds `8888`/`8889` — set `"autoPort": false` in `.wp-env.json`:

```json
{
"autoPort": false
}
```

Automatic port selection is also disabled whenever the `CI` environment variable is set, regardless of the `autoPort` value, so test runs stay deterministic.

Several types of strings can be passed into the `core`, `plugins`, `themes`, and `mappings` fields.

Expand Down
2 changes: 1 addition & 1 deletion packages/env/lib/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ module.exports = function cli() {
args.option( 'auto-port', {
type: 'boolean',
describe:
'Automatically find available ports when configured ports are busy. Overrides the .wp-env.json "autoPort" setting.',
'Also fall back to the next available port when explicitly configured ports are busy. By default, only the standard ports 8888/8889 auto-fall-back. Overrides the .wp-env.json "autoPort" setting.',
} );
},
withSpinner( env.start )
Expand Down
20 changes: 10 additions & 10 deletions packages/env/lib/commands/start.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,16 @@ const { getRuntime, getSavedRuntime, saveRuntime } = require( '../runtime' );
/**
* Starts the development server.
*
* @param {Object} options
* @param {Object} options.spinner A CLI spinner which indicates progress.
* @param {boolean} options.update If true, update sources.
* @param {string} options.xdebug The Xdebug mode to set.
* @param {string} options.spx The SPX mode to set.
* @param {boolean} options.scripts Indicates whether or not lifecycle scripts should be executed.
* @param {boolean} options.debug True if debug mode is enabled.
* @param {string} options.runtime The runtime to use ('docker' or 'playground').
* @param {boolean} options.autoPort If true, automatically find available ports when configured ports are busy.
* @param {string|null} options.config Path to a custom .wp-env.json configuration file.
* @param {Object} options
* @param {Object} options.spinner A CLI spinner which indicates progress.
* @param {boolean} options.update If true, update sources.
* @param {string} options.xdebug The Xdebug mode to set.
* @param {string} options.spx The SPX mode to set.
* @param {boolean} options.scripts Indicates whether or not lifecycle scripts should be executed.
* @param {boolean} options.debug True if debug mode is enabled.
* @param {string} options.runtime The runtime to use ('docker' or 'playground').
* @param {boolean|undefined} options.autoPort Tri-state: `true` enables automatic port fallback for every port (including user-set ones); `false` disables fallback even on default ports; `undefined` (the typical case — flag not supplied) defers to `.wp-env.json`'s `autoPort` field, where unset/`null` means "auto-fallback only on default ports `8888`/`8889`".
* @param {string|null} options.config Path to a custom .wp-env.json configuration file.
*/
module.exports = async function start( {
spinner,
Expand Down
55 changes: 37 additions & 18 deletions packages/env/lib/config/load-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,12 @@ const { createPortResolver } = require( '../resolve-available-ports' );
/**
* Loads any configuration from a given directory.
*
* @param {string} configDirectoryPath The directory we want to load the config from.
* @param {string|null} customConfigPath Optional custom config file path.
* @param {Object} options Options for loading the config.
* @param {boolean} options.resolvePorts Whether HTTP ports should be resolved for this command.
* @param {boolean} options.autoPort CLI override for automatic port selection.
* @param {Object} options.spinner A CLI spinner used by the port resolver.
* @param {string} configDirectoryPath The directory we want to load the config from.
* @param {string|null} customConfigPath Optional custom config file path.
* @param {Object} options Options for loading the config.
* @param {boolean} options.resolvePorts Whether HTTP ports should be resolved for this command.
* @param {boolean|undefined} options.autoPort Tri-state CLI override for automatic port selection: `true` enables fallback for all ports, `false` disables fallback even on default ports, `undefined` defers to `config.autoPort` (which itself is tri-state — `null`/`undefined` means "fallback only on default ports").
* @param {Object} options.spinner A CLI spinner used by the port resolver.
*
* @return {Promise<WPConfig>} The config object we've loaded.
*/
Expand Down Expand Up @@ -93,25 +93,44 @@ module.exports = async function loadConfig(
customConfigPath
);

let portResolver;
if ( resolvePorts ) {
let shouldAutoPort =
autoPort !== undefined ? autoPort : config.autoPort;
// Compute the tri-state auto-port mode. Precedence: CLI option beats
// config.autoPort. CLI `true`/`false` are explicit; `undefined` defers
// to the parsed config value (which itself is tri-state — `null` /
// `undefined` means "unset, use the new defaults-only behavior").
let autoPortMode;
const effectiveAutoPort =
autoPort !== undefined ? autoPort : config.autoPort;
if ( effectiveAutoPort === true ) {
autoPortMode = 'all';
} else if ( effectiveAutoPort === false ) {
autoPortMode = 'off';
} else {
autoPortMode = 'defaults-only';
}

// Automatic port selection is undesirable in CI where determinism matters.
if ( process.env.CI ) {
shouldAutoPort = false;
}
// Automatic port selection is undesirable in CI where determinism matters.
if ( process.env.CI ) {
autoPortMode = 'off';
}

if ( shouldAutoPort ) {
portResolver = createPortResolver( spinner );
}
let portResolver;
if ( resolvePorts && autoPortMode !== 'off' ) {
portResolver = createPortResolver( spinner );
}

// Read the per-port provenance attached by `parseConfig`. Falls back to
// an empty set so callers that bypass `parseConfig` (e.g. some tests)
// keep working.
const defaultOriginPorts = config.__defaultOriginPorts ?? new Set();

// Make sure to perform any additional post-processing that
// may be needed before the config object is ready for
// consumption elsewhere in the tool.
config = await postProcessConfig( config, { portResolver } );
config = await postProcessConfig( config, {
portResolver,
autoPortMode,
defaultOriginPorts,
} );

return {
name: path.basename( configDirectoryPath ),
Expand Down
116 changes: 112 additions & 4 deletions packages/env/lib/config/parse-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const mergeConfigs = require( './merge-configs' );
* @typedef WPRootConfigOptions
* @property {number} port The port to use in the development environment.
* @property {number} testsPort The port to use in the tests environment.
* @property {boolean} autoPort Whether to automatically select a nearby available HTTP port.
* @property {boolean|null} autoPort Tri-state: `null` (unset, default behavior — auto-fallback only on default ports), `true` (auto-fallback for all ports), `false` (strict for all ports).
* @property {Object.<string, string|null>} lifecycleScripts The scripts to run at certain points in the command lifecycle.
* @property {Object.<string, string|null>} lifecycleScripts.afterStart The script to run after the "start" command has completed.
* @property {Object.<string, string|null>} lifecycleScripts.afterClean The script to run after the "clean" command has completed.
Expand Down Expand Up @@ -90,7 +90,7 @@ const DEFAULT_ENVIRONMENT_CONFIG = {
themes: [],
port: 8888,
testsPort: 8889,
autoPort: false,
autoPort: null,
mysqlPort: null,
phpmyadmin: false,
phpmyadminPort: null,
Expand Down Expand Up @@ -159,12 +159,115 @@ async function parseConfig(

// Merge all of our configs so that we have a complete object
// containing the desired options in order of precedence.
return mergeConfigs(
const merged = mergeConfigs(
defaultConfig,
localConfig ?? {},
overrideConfig ?? {},
environmentVarOverrides
);

// Track which HTTP ports came from `DEFAULT_ENVIRONMENT_CONFIG` versus
// any user-supplied source. This is consumed by the port resolver to
// decide whether to silently fall back to the next available port (for
// default-origin ports) or to surface a strict port-busy error (for
// user-set ports). Stored as a non-enumerable property so it does not
// participate in `mergeConfig` iteration, JSON serialization, or
// `toEqual` equality checks performed elsewhere.
const defaultOriginPorts = computeDefaultOriginPorts(
localConfig,
overrideConfig,
environmentVarOverrides
);
Object.defineProperty( merged, '__defaultOriginPorts', {
value: defaultOriginPorts,
enumerable: false,
writable: false,
configurable: false,
} );

return merged;
}

/**
* Computes the set of HTTP port keys whose effective value comes from
* `DEFAULT_ENVIRONMENT_CONFIG` (i.e. no user-supplied source provided them).
*
* The returned Set contains zero or more of the strings `'development.port'`
* and `'tests.port'`. Each key is included when none of the user-supplied
* sources (root `.wp-env.json`, `.wp-env.override.json`, or environment
* variables) provide a value for that port.
*
* @param {Object|null} localConfig The parsed local config, or null when absent.
* @param {Object|null} overrideConfig The parsed override config, or null when absent.
* @param {Object} environmentVarOverrides The config-shaped object derived from env vars.
*
* @return {Set<string>} The set of default-origin port keys.
*/
function computeDefaultOriginPorts(
localConfig,
overrideConfig,
environmentVarOverrides
) {
const result = new Set();

const isDevelopmentPortUserSet =
layerSetsDevelopmentPort( localConfig ) ||
layerSetsDevelopmentPort( overrideConfig ) ||
layerSetsDevelopmentPort( environmentVarOverrides );

const isTestsPortUserSet =
layerSetsTestsPort( localConfig ) ||
layerSetsTestsPort( overrideConfig ) ||
layerSetsTestsPort( environmentVarOverrides );

if ( ! isDevelopmentPortUserSet ) {
result.add( 'development.port' );
}
if ( ! isTestsPortUserSet ) {
result.add( 'tests.port' );
}

return result;
}

/**
* Whether the given config layer provides a value for the development HTTP port.
*
* @param {Object|null|undefined} layer The config layer to inspect.
*
* @return {boolean} True when the layer sets the development port.
*/
function layerSetsDevelopmentPort( layer ) {
if ( ! layer ) {
return false;
}
if ( layer.port !== undefined ) {
return true;
}
if ( layer.env?.development?.port !== undefined ) {
return true;
}
return false;
}

/**
* Whether the given config layer provides a value for the tests HTTP port.
*
* @param {Object|null|undefined} layer The config layer to inspect.
*
* @return {boolean} True when the layer sets the tests port.
*/
function layerSetsTestsPort( layer ) {
if ( ! layer ) {
return false;
}
if ( layer.testsPort !== undefined ) {
return true;
}
if ( layer.env?.tests?.port !== undefined ) {
return true;
}
return false;
}

/**
Expand Down Expand Up @@ -388,7 +491,12 @@ async function parseRootConfig( configFile, rawConfig, options ) {
parsedConfig.testsPort = rawConfig.testsPort;
}
if ( rawConfig.autoPort !== undefined ) {
if ( typeof rawConfig.autoPort !== 'boolean' ) {
// `null` is a valid tri-state value meaning "unset" (the default).
// Only user-provided autoPort values must be booleans.
if (
rawConfig.autoPort !== null &&
typeof rawConfig.autoPort !== 'boolean'
) {
throw new ValidationError(
`Invalid ${ configFile }: "autoPort" must be a boolean.`
);
Expand Down
Loading
Loading