# Troubleshooting Guide - Docker MCP Server
## 1. Connection Issues
### 1.1 MCP Server Failed to Connect
#### Symptom
```
claude mcp list
❯ 1. docker-mcp-py ✘ failed · Enter to view details
```
#### Root Causes & Solutions
##### Cause 1: Import Path Error
**Error Message:**
```python
<coroutine object main at 0x7fd051052c20>
sys:1: RuntimeWarning: coroutine 'main' was never awaited
```
**Solution:**
```python
# File: docker_mcp_server.py
# ❌ Wrong - Incorrect import path
from src.docker_mcp.server import main
# ✅ Correct - Proper import path
from src.server import main
```
##### Cause 2: Missing Async Context
**Error Message:**
```python
RuntimeWarning: coroutine 'main' was never awaited
```
**Solution:**
```python
# File: docker_mcp_server.py
# ❌ Wrong - Missing async context
if __name__ == "__main__":
sys.exit(main())
# ✅ Correct - Proper async execution
import asyncio
if __name__ == "__main__":
asyncio.run(main())
```
##### Cause 3: Docker Image Not Built
**Error Message:**
```bash
docker: Error response from daemon: Unable to find image 'docker-mcp-py:latest'
```
**Solution:**
```bash
# Build the Docker image
cd /home/debian/docker-mcp-py
sudo docker build -t docker-mcp-py:latest .
# Verify image exists
sudo docker images | grep docker-mcp-py
```
##### Cause 4: Docker Socket Permission
**Error Message:**
```
Permission denied: '/var/run/docker.sock'
```
**Solution:**
```bash
# Check socket permissions
ls -la /var/run/docker.sock
# Add user to docker group
sudo usermod -aG docker $USER
# Or use sudo in start script
sudo docker run -v /var/run/docker.sock:/var/run/docker.sock ...
```
### 1.2 Testing MCP Connection
#### Quick Test Script
```bash
# Test basic JSON-RPC communication
echo '{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": {"name": "test", "version": "1.0.0"}}}' | ./start-docker.sh
# Expected response:
# {"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2024-11-05","capabilities":{...},"serverInfo":{"name":"docker-mcp-py","version":"0.3.0"}}}
```
#### Comprehensive Test
```bash
# Create test script
cat > test_mcp_connection.sh << 'EOF'
#!/bin/bash
echo "Testing Docker MCP Server..."
# Test 1: Initialize
echo "1. Testing initialization..."
RESPONSE=$(echo '{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": {"name": "test", "version": "1.0.0"}}}' | timeout 5 ./start-docker.sh 2>&1)
if echo "$RESPONSE" | grep -q '"serverInfo"'; then
echo "✅ Initialization successful"
else
echo "❌ Initialization failed"
echo "$RESPONSE"
exit 1
fi
# Test 2: List tools
echo "2. Testing tool listing..."
echo '{"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}' | timeout 5 ./start-docker.sh 2>&1 | grep -q "create-container"
if [ $? -eq 0 ]; then
echo "✅ Tools listing successful"
else
echo "❌ Tools listing failed"
exit 1
fi
echo "All tests passed!"
EOF
chmod +x test_mcp_connection.sh
./test_mcp_connection.sh
```
## 2. Docker Operation Errors
### 2.1 Container Creation Failed
#### Error: Image Not Found
```json
{
"error": "404 Client Error: Not Found for url: http+docker://localhost/v1.41/images/create"
}
```
**Solution:**
```bash
# Pull image first
sudo docker pull nginx:latest
# Or use full image path
{
"image": "docker.io/library/nginx:latest"
}
```
#### Error: Port Already in Use
```
Error: Bind for 0.0.0.0:8080 failed: port is already allocated
```
**Solution:**
```bash
# Check what's using the port
sudo lsof -i :8080
# Use different port
{
"ports": {"80": "8081"}
}
```
### 2.2 Compose Deployment Issues
#### Error: YAML Parse Error
```
yaml.scanner.ScannerError: mapping values are not allowed here
```
**Solution:**
```yaml
# Ensure proper YAML formatting
version: '3.8' # Quotes for version
services:
web:
image: nginx
ports:
- "8080:80" # Quotes for port mapping
```
#### Error: Network Not Found
```
Error: Network project_default not found
```
**Solution:**
```bash
# Create network manually
sudo docker network create project_default
# Or let Compose create it
sudo docker-compose up --force-recreate
```
## 3. Performance Issues
### 3.1 Slow Container Listing
#### Symptom
Container listing takes > 5 seconds
#### Solution
```python
# Implement filtering at query level
async def list_containers(filters=None):
# ❌ Slow - Get all then filter
containers = docker_client.containers.list(all=True)
return [c for c in containers if matches_filter(c, filters)]
# ✅ Fast - Filter at Docker level
return docker_client.containers.list(all=True, filters=filters)
```
### 3.2 Memory Leaks
#### Symptom
Memory usage grows over time
#### Solution
```python
# Close Docker clients properly
async def execute_docker_operation():
client = docker.from_env()
try:
# Perform operations
result = await operation(client)
finally:
client.close() # Always close
return result
```
## 4. Security Issues
### 4.1 Exposed Secrets in Logs
#### Problem
Sensitive data appearing in logs
#### Solution
```python
# Implement log sanitization
import re
def sanitize_logs(message):
# Redact common secret patterns
patterns = [
(r'(password|token|secret|key)=\S+', r'\1=***REDACTED***'),
(r'Bearer \S+', 'Bearer ***REDACTED***'),
]
for pattern, replacement in patterns:
message = re.sub(pattern, replacement, message, flags=re.IGNORECASE)
return message
```
### 4.2 Command Injection
#### Problem
Unsanitized user input in commands
#### Solution
```python
# Use parameterized commands
# ❌ Vulnerable
command = f"docker run {user_input}"
# ✅ Safe
docker_client.containers.run(
image=validated_image,
command=shlex.quote(user_command)
)
```
## 5. Common Configuration Mistakes
### 5.1 Claude.json Configuration
#### Wrong Configuration
```json
{
"mcpServers": {
"docker-mcp-py": {
"type": "stdio",
"command": "python docker_mcp_server.py", // Won't work in container
"args": []
}
}
}
```
#### Correct Configuration
```json
{
"mcpServers": {
"docker-mcp-py": {
"type": "stdio",
"command": "/home/debian/docker-mcp-py/start-docker.sh",
"args": [],
"env": {}
}
}
}
```
### 5.2 Dockerfile Issues
#### Missing Python Path
```dockerfile
# ❌ Wrong - Python can't find modules
CMD ["python", "docker_mcp_server.py"]
# ✅ Correct - Set PYTHONPATH
ENV PYTHONPATH=/app/src
CMD ["python", "docker_mcp_server.py"]
```
## 6. Debug Procedures
### 6.1 Enable Debug Logging
```bash
# Set environment variables
export MCP_DEBUG=true
export PYTHONUNBUFFERED=1
export LOG_LEVEL=DEBUG
# Run with debug output
./start-docker.sh 2>&1 | tee debug.log
```
### 6.2 Container Inspection
```bash
# Check if MCP container is running
sudo docker ps | grep docker-mcp-py
# View container logs
sudo docker logs $(sudo docker ps -q -f "ancestor=docker-mcp-py:latest")
# Interactive debugging
sudo docker run -it --rm \
-v /var/run/docker.sock:/var/run/docker.sock \
--entrypoint /bin/bash \
docker-mcp-py:latest
```
### 6.3 Network Debugging
```bash
# Test Docker API connectivity
curl --unix-socket /var/run/docker.sock http://localhost/version
# Check MCP server response
echo '{"jsonrpc": "2.0", "id": 1, "method": "ping"}' | nc -U /tmp/mcp.sock
```
## 7. Recovery Procedures
### 7.1 Full Reset
```bash
#!/bin/bash
# Complete reset script
echo "Resetting Docker MCP Server..."
# 1. Stop any running MCP containers
sudo docker ps -q -f "ancestor=docker-mcp-py:latest" | xargs -r sudo docker stop
# 2. Remove old image
sudo docker rmi docker-mcp-py:latest 2>/dev/null
# 3. Clean build cache
sudo docker builder prune -f
# 4. Rebuild image
cd /home/debian/docker-mcp-py
sudo docker build -t docker-mcp-py:latest .
# 5. Test connection
./test_mcp_connection.sh
echo "Reset complete!"
```
### 7.2 Quick Fix Script
```bash
#!/bin/bash
# Quick fix for common issues
echo "Applying quick fixes..."
# Fix 1: Correct import path
sed -i 's/from src.docker_mcp.server/from src.server/' docker_mcp_server.py
# Fix 2: Add asyncio.run
if ! grep -q "asyncio.run" docker_mcp_server.py; then
sed -i 's/sys.exit(main())/asyncio.run(main())/' docker_mcp_server.py
sed -i '1a import asyncio' docker_mcp_server.py
fi
# Fix 3: Rebuild image
sudo docker build -t docker-mcp-py:latest .
# Fix 4: Update Claude config
if [ -f ~/.claude.json ]; then
jq '.mcpServers["docker-mcp-py"].command = "'$(pwd)'/start-docker.sh"' ~/.claude.json > ~/.claude.json.tmp
mv ~/.claude.json.tmp ~/.claude.json
fi
echo "Fixes applied!"
```
## 8. Monitoring & Alerts
### 8.1 Health Check Script
```bash
#!/bin/bash
# Health monitoring script
check_mcp_health() {
# Check if Docker is running
if ! sudo systemctl is-active --quiet docker; then
echo "ALERT: Docker service is down"
return 1
fi
# Check MCP server response
RESPONSE=$(echo '{"jsonrpc": "2.0", "id": 1, "method": "ping"}' | timeout 5 ./start-docker.sh 2>&1)
if [ $? -ne 0 ]; then
echo "ALERT: MCP server not responding"
return 1
fi
echo "OK: All systems operational"
return 0
}
# Run health check every 5 minutes
while true; do
check_mcp_health
sleep 300
done
```
## 9. FAQ
### Q: Why does the MCP server show as "failed" in Claude Code?
**A:** Usually due to import path errors or missing async context. Check the docker_mcp_server.py file.
### Q: Can I run multiple instances of the MCP server?
**A:** Yes, but ensure they use different container names to avoid conflicts.
### Q: How do I update the MCP server?
**A:** Pull latest code, rebuild Docker image, restart Claude Code.
### Q: Why are my environment variables not working?
**A:** Ensure they're passed through both the shell script and Docker run command.
### Q: How can I add custom Docker registries?
**A:** Configure Docker daemon with registry credentials, or pass auth in image names.
---
**Document Version**: 1.0.0
**Last Updated**: 2025-08-28
**Support Contact**: GitHub Issues