[BUG] Docker-based MCP server containers not stopped when session ends
Preflight Checklist
- [x] I have searched existing issues and this hasn't been reported yet
- [x] This is a single bug report (please file separate reports for different bugs)
- [x] I am using the latest version of Claude Code
What's Wrong?
When an MCP server is configured to run via docker run in .mcp.json, the Docker container keeps running after closing Claude Code. This does not happen with non-Docker MCP servers (e.g., npx-based), which are properly cleaned up as direct child processes.
The root cause: docker run is the child process of Claude Code, but the actual container runs under the Docker daemon. Killing the docker run process does not kill the container.
A SessionEnd hook workaround is unsafe because stopping containers by image name (e.g., docker stop $(docker ps -q --filter ancestor=image-name)) would kill containers used by other concurrent Claude Code sessions — there's no way to map a container to a specific session.
What Should Happen?
The Docker container should be stopped when the Claude Code session ends, just like npx-based MCP servers are terminated.
Suggested fix: Claude Code could capture the Docker container ID when starting a Docker-based MCP server and run docker stop <container_id> during session cleanup. This would safely stop only the container belonging to the ending session.
Steps to Reproduce
- Configure a Docker-based MCP server in
.mcp.json:
``json``
{
"mcpServers": {
"postgres": {
"type": "stdio",
"command": "docker",
"args": ["run", "-i", "--rm", "crystaldba/postgres-mcp"]
}
}
}
- Start a Claude Code session (the MCP container starts automatically)
- Close/exit the Claude Code session
- Run
docker ps— the container is still running - Compare: configure an MCP server with
npxinstead ofdocker— it gets cleaned up properly on session end
Claude Model
Opus
Is this a regression?
I don't know
Claude Code Version
2.1.59
Platform
Anthropic API
Operating System
Other Linux
Terminal/Shell
Other
Additional Information
- OS: Arch Linux (6.18.9-arch1-2)
- Shell: fish
- The
--rmflag ondocker runonly removes the container after it stops, but nothing triggers the stop on session end.
This issue has 9 comments on GitHub. Read the full discussion on GitHub ↗