Skip to content
How to fix git worktree port conflicts without hashing folder names

How to fix git worktree port conflicts without hashing folder names

Git worktree port conflicts start when two checkouts both want Vite's 5173 or Node's 9229. Store one base port per worktree and derive the API and debugger ports from it.

Aaron Delasy
Aaron DelasyFounder

Git worktree port conflicts happen because worktrees separate files but share one localhost, so two dev servers still fight over Vite's 5173 or Node's debugger port 9229. My main repository has 46 worktree folders as I write this, most made by agents, and a few of them run a full dev stack at the same time.

A worktree gives each agent its own files and shares everything else. Git keeps one object store, one config and one hooks folder for every worktree (gitrepository-layout), and the operating system keeps one set of ports for all of them. So a second dev server dies with EADDRINUSE, or slides to the next port and leaves its tests aimed at the wrong branch, or logs out the app running next door.

Find the process holding the port before you change anything

On Linux, ss -ltnp names the process listening on each TCP port, and /proc/<pid>/cwd names the folder it started in, which is the worktree to blame.

bash
ss -ltnp 'sport = :3000'
readlink /proc/<pid>/cwd

For a Node 24 server, ss printed users:(("MainThread",pid=2126104,fd=18)). MainThread is a thread name, which surprised me the first time, so the pid and the working directory behind it are the parts worth reading. A path ending in (deleted) belongs to a server from a worktree I already removed, and that server still holds its port.

macOS has neither ss nor /proc. There, lsof -nP -iTCP:3000 -sTCP:LISTEN finds the listener and lsof -a -p <pid> -d cwd prints its working directory.

Vite and Node hide a taken port instead of failing

Vite's dev server starts on port 5173 and, when that port is taken, tries the next available one unless server.strictPort is set to true.

So the second worktree's app comes up on 5174 and nothing looks wrong. Its Playwright baseURL and its OAuth callback still say 5173, where the first worktree's app is serving the other branch. I'd rather have the crash, because a test run that passes against the wrong branch costs me more than a red one.

Two worktrees side by side: in wt-a, Vite listens on localhost:5173 and node --inspect on 127.0.0.1:9229; in wt-b, Vite moves to localhost:5174 and the inspector fails with address already in use while the process keeps running, and wt-b's Playwright baseURL and debugger cross over to wt-a's code

Node's debugger port fails just as quietly. node --inspect listens on 127.0.0.1:9229 by default (Node debugging guide). When I started two processes with --inspect=127.0.0.1:9339 on Node 24.22.1, the second printed Starting inspector on 127.0.0.1:9339 failed: address already in use, kept running and exited with 0. A debugger that attaches to that port reaches the first worktree's process, and my breakpoints never fire in the code I'm editing.

Each fix is one line. server.strictPort: true in vite.config.ts makes the second server exit, and node --inspect=127.0.0.1:$DEBUG_PORT takes the debugger port from the worktree's env file.

Hashing the folder path into a port still collides

Hashing a worktree's path into 1 of 99 port offsets gives 5 worktrees a 9.7% chance of a shared port, which the hook never checks for.

When I searched this exact phrase on 28 November 2026, Google's AI Overview recommended a post-checkout hook that runs cksum on $PWD, maps the result to an offset from 1 to 99 and writes PORT=$((3000 + OFFSET)) into an untracked .env.local. Wietse Venema's version hashes the path with SHA-256 into 400 slots of 5 ports starting at 8000. Its odds are better, and it fails the same way.

This is the birthday problem. Five worktrees in 99 offsets all miss each other with probability 98/99 × 97/99 × 96/99 × 95/99 = 90.3%, so two of them collide 9.7% of the time, and 10 worktrees collide 37.5% of the time. Venema's 400 slots cut those to 2.5% and 10.7%.

Moving or renaming a worktree changes its path, so a path hash moves its port too, and every bookmark and OAuth callback that named the old port breaks. The hook also lives in .git/hooks, which git never commits, so a teammate who clones the repository gets no hook unless the team points core.hooksPath at a tracked folder (githooks).

Grouped bar chart of the chance that two worktrees share a port: with 99 cksum offsets it is 1.0% for 2 worktrees, 3.0% for 3, 9.7% for 5, 25.2% for 8 and 37.5% for 10; with 400 SHA-256 slots it is 0.2%, 0.7%, 2.5%, 6.8% and 10.7%

Compare the ways to give each worktree its own port

Of these six schemes, only a slot registry keeps each worktree's port through restarts and git worktree move with no collisions and no sudo, when worktrees are created in turn.

SchemeTwo worktrees collideSame port after a restartSame port after git worktree moveNeeds sudoBest for
Path hash, 99 offsets (cksum)9.7% at 5 worktreesYesNoNo2 or 3 worktrees, one service
Path hash, 400 slots of 5 ports (SHA-256)2.5% at 5 worktreesYesNoNoA few worktrees, up to 5 services each
Slot registry (lowest free number, stored once)Never, when slots are claimed in turnYesYes, in my testNoMany worktrees with multi-service stacks
Port 0 (the OS picks a free port)NeverNoNoNoTest runs that read the port back
Loopback address per worktree (127.0.0.2, 127.0.0.3)Only when two get the same addressYesDepends on how addresses are givenOn macOS yes, on Linux noApps with port 3000 hardcoded somewhere
Container per worktree with a templated host portAs often as its host-port schemeYesDepends on the host-port schemeNoStacks with a database and a cache

An OAuth provider can't call back a port 0 server after a restart, because the port changes on every start. On Linux, 127.0.0.2 and 127.0.0.3 both bound port 3999 in my test with no setup, while macOS needs an lo0 alias per address. A container per worktree still takes its host port from somewhere, like "${WEB_PORT:-3000}:3000" in the Compose file, and it costs a full stack of RAM per worktree. For most repositories I'd skip the containers and claim slots.

Give each worktree one base port and derive the rest

The repository behind Aldena gives every worktree one web port, such as 3118, and derives the API (4118), the state Worker (5118) and the MCP server (14118) from it.

Three checkouts of one repository: the main checkout on web 3000, api 4000, state Worker 5000 and MCP server 14000; worktree A on 3118, 4118, 5118 and 14118; worktree B on 3302, 4302, 5302 and 14302; each with its own Compose project, dev container and .wrangler/state database, under the rule api = web + 1000, state = web + 2000, MCP = web + 11000

The main checkout keeps 3000, 4000, 5000 and 14000, and the docs preview sits at the web port plus 5000. When the worktree script creates a checkout, it sets up the ports, the .env files, the dependencies and a migrated, seeded database, and the checkout gets its own Compose project, dev container and .wrangler/state database. One number per worktree has to be unique, and nobody edits ports by hand.

The ports live in the container's environment, so ./dx.sh printenv WEB_PORT API_PORT STATE_PORT MCP_PORT prints a checkout's four numbers. dx.sh runs commands without a shell, so a $WEB_PORT on its command line expands on the host, where it's empty, and I pass the literal port.

Without that tooling, one script gets most of the way. The slot registry below, tested on git 2.39.5, takes the lowest number no other worktree holds, stores it in the worktree's own admin folder under .git/worktrees/, and writes a block of 10 ports into .env.local:

sh
#!/bin/sh
# wt-port: run inside a worktree. Claims the lowest free slot once, then writes .env.local.
set -eu
cd "$(git rev-parse --show-toplevel)"
common=$(git rev-parse --path-format=absolute --git-common-dir)
gitdir=$(git rev-parse --path-format=absolute --git-dir)

if [ "$gitdir" = "$common" ]; then
  slot=0
else
  if [ ! -f "$gitdir/port-slot" ]; then
    slot=1
    while cat "$common"/worktrees/*/port-slot 2>/dev/null | grep -qx "$slot"; do
      slot=$((slot + 1))
    done
    echo "$slot" > "$gitdir/port-slot"
  fi
  slot=$(cat "$gitdir/port-slot")
fi

base=$((3000 + slot * 10))
printf 'PORT=%s\nAPI_PORT=%s\nDEBUG_PORT=%s\n' "$base" "$((base + 1))" "$((base + 2))" > .env.local
echo "slot $slot: web $base, api $((base + 1)), debugger $((base + 2))"

In a throwaway repository the main checkout kept 3000 and two new worktrees got 3010 and 3020. The first one still had 3010 after git worktree move, because a worktree's admin folder keeps its name when the worktree moves. Removing the second deleted its admin folder, and the next new worktree got 3020 back.

Four steps of the slot registry in a throwaway repository: git worktree add gives wt-a slot 1 on web 3010 and wt-b slot 2 on web 3020 while the main checkout keeps slot 0 on 3000; git worktree move keeps wt-a on slot 1 because its admin folder keeps its name; git worktree remove deletes wt-b's admin folder and frees slot 2; the next git worktree add gives wt-c slot 2 on web 3020

To run it when a worktree is created, I copied it to .git/wt-port and called it from post-checkout. Git runs that hook after git worktree add too, with the null ref as its first argument (githooks), and the hook below exits early for any other ref, so later branch switches leave the slot alone. The same hook can warm the new worktree's build cache.

sh
#!/bin/sh
[ "$1" = 0000000000000000000000000000000000000000 ] || exit 0
sh "$(git rev-parse --path-format=absolute --git-common-dir)/wt-port"

Add .env.local to .gitignore first. Without that line, git worktree remove refused in my test, because it counted the untracked file as a change. Two worktrees created at the same instant can claim the same slot, so create them one at a time or wrap the script in flock. And keep the main checkout's .env out of new worktrees, because a copy brings its ports along.

Separate ports still share cookies, databases and Redis

Browser cookies ignore the port, as RFC 6265 § 8.5 says, so apps on localhost:3991 and localhost:3992 read and overwrite each other's cookies.

I checked it in Playwright's Chromium. A cookie set by localhost:3991 came back in the Cookie header of a request to localhost:3992, and a request to 127.0.0.2:3992 carried none. So when two worktrees' apps both call their cookie session, logging into one overwrites the other's, and the other app receives a session its own database never issued and logs me out.

A Chromium cookie jar holding one cookie for host localhost, session=from-3991: GET localhost:3991 sets it, GET localhost:3992 sends it back as a different port with the same cookie, and GET 127.0.0.2:3992 sends no cookie because it is a different host

A cookie named after the slot (session_3010) fixes it. So does a loopback address per worktree, because cookies are scoped by host and 127.0.0.2 is a different host from 127.0.0.3.

Databases and caches collide the same way once two worktrees reach them by one name. A migration on one branch changes the schema under the other, so name the database after the slot (app_dev_3010) and give Redis a key prefix per slot. Fixed host ports in a Compose file, like "5432:5432", fail exactly like dev servers do, so take them from .env.local too. My own repository sidesteps most of this with a local database per checkout under .wrangler/state.

How ports work in Aldena's sandboxes

Aldena gives each conversation its own sandbox, and every process an agent starts there, its dev server included, runs inside that conversation's sandbox.

Aldena is my product, so read this section as the pitch it is. Each sandbox in a project runs on the team's sandbox provider, such as Boat, with its own CPU and RAM. The agents clone the repository there, start the app and run its tests, and nobody SSHes into anything.

Inside one conversation, an agent and the agents it delegates to share one sandbox, and its ports with it. The Delivery agent hands work to one delegate at a time, so two agents never edit the same checkout at once.

Aldena project canvas where the busy agent cards list their tasks, with the Intake agent delegating to the Requirements and Delivery agents, Delivery delegating to the Backend Build, Frontend Build and Code Review agents, both build agents delegating to Code Review, and the link from Delivery to Code Review lit green while work moves along it

Databases move into the project's setup script, which runs once on each new sandbox with sudo and the project's environment variables. Agents run without sudo or Docker, so the setup script installs and starts PostgreSQL or Redis, and each conversation's sandbox gets its own copy. A sandbox sleeps 30 minutes after its last command and keeps its files until the conversation sits quiet for 7 days. The sandbox provider bills machine time to the team's own account (Boat bills by the second), and Aldena adds nothing on top of the team plan.

On my laptop the worktree script still hands out ports, because there every agent shares one localhost.

Ready when you are

Spin up your first project.

One project per client, product, or piece of work, staffed with intake, requirements, build and code review agents.