[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M757C4BGKQ2SKHAFPSTZ0DC1":3,"skill-same:01M757C4BGKQ2SKHAFPSTZ0DC1":84},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":44,"commitSha":45,"skillDirectory":46,"forksCount":14,"repositoryHtmlUrl":47,"repositoryHomepageUrl":6,"ownerHtmlUrl":48,"ownerBlogUrl":49,"ownerDescription":50,"updatedAt":51,"install":52,"resources":65},"01M757C4BGKQ2SKHAFPSTZ0DC1","docker-management",null,"Manage Docker containers, images, volumes, networks, and Compose stacks — lifecycle ops, debugging, cleanup, and Dockerfile optimization.","SatangThevalue\u002Fai-skills","SatangThevalue","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F17944930?v=4","01M756VHQQ58XSM5PDS03W79VY","Sa-Tang","01M756VHRNYXRY7HM230S4YHVV",0,"MIT","https:\u002F\u002Fgithub.com\u002FSatangThevalue\u002Fai-skills\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fdocker-management\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: docker-management\ndescription: Manage Docker containers, images, volumes, networks, and Compose stacks — lifecycle ops, debugging, cleanup, and Dockerfile optimization.\nversion: 1.0.0\nauthor: sprmn24\nlicense: MIT\nplatforms: [linux, macos, windows]\nmetadata:\n  hermes:\n    tags: [docker, containers, devops, infrastructure, compose, images, volumes, networks, debugging]\n    category: devops\n    requires_toolsets: [terminal]\n---\n\n# Docker Management\n\nManage Docker containers, images, volumes, networks, and Compose stacks using standard Docker CLI commands. No additional dependencies beyond Docker itself.\n\n## When to Use\n\n- Run, stop, restart, remove, or inspect containers\n- Build, pull, push, tag, or clean up Docker images\n- Work with Docker Compose (multi-service stacks)\n- Manage volumes or networks\n- Debug a crashing container or analyze logs\n- Check Docker disk usage or free up space\n- Review or optimize a Dockerfile\n\n## Prerequisites\n\n- Docker Engine installed and running\n- User added to the `docker` group (or use `sudo`)\n- Docker Compose v2 (included with modern Docker installations)\n\nQuick check:\n\n```bash\ndocker --version && docker compose version\n```\n\n- `references\u002Fpostgres-miner-sudo-askpass.md` — Handling memory-resident PostgreSQL cryptominers when the user provides a password using the `SUDO_ASKPASS` technique.\n- `references\u002Fmemory-resident-malware-removal.md` — General workflow for identifying and removing memory-resident cryptominers.\n\n\n| Task | Command |\n|------|---------|\n| Run container (background) | `docker run -d --name NAME IMAGE` |\n| Stop + remove | `docker stop NAME && docker rm NAME` |\n| View logs (follow) | `docker logs --tail 50 -f NAME` |\n| Shell into container | `docker exec -it NAME \u002Fbin\u002Fsh` |\n| List all containers | `docker ps -a` |\n| Build image | `docker build -t TAG .` |\n| Compose up | `docker compose up -d` |\n| Compose down | `docker compose down` |\n| Disk usage | `docker system df` |\n| Cleanup dangling | `docker image prune && docker container prune` |\n\n## Procedure\n\n### 1. Identify the domain\n\nFigure out which area the request falls into:\n\n- **Container lifecycle** → run, stop, start, restart, rm, pause\u002Funpause\n- **Container interaction** → exec, cp, logs, inspect, stats\n- **Image management** → build, pull, push, tag, rmi, save\u002Fload\n- **Docker Compose** → up, down, ps, logs, exec, build, config\n- **Volumes & networks** → create, inspect, rm, prune, connect\n- **Troubleshooting** → log analysis, exit codes, resource issues\n\n### 2. Container operations\n\n**Restart Policies (Ensuring Resilience):**\nWhen deploying critical infrastructure (databases, proxies, APIs), ALWAYS set the restart policy to `unless-stopped`. This ensures they spin back up automatically after a VPS reboot (check reboot via `uptime`).\n```bash\n# Update existing exited\u002Frunning containers to auto-restart\ndocker update --restart unless-stopped \u003Ccontainer1> \u003Ccontainer2>\n```\n\n**Run a new container:**\n\n```bash\n# Detached service with port mapping\ndocker run -d --name web -p 8080:80 nginx\n\n# With environment variables\ndocker run -d -e POSTGRES_PASSWORD=secret -e POSTGRES_DB=mydb --name db postgres:16\n\n# With persistent data (named volume)\ndocker run -d -v pgdata:\u002Fvar\u002Flib\u002Fpostgresql\u002Fdata --name db postgres:16\n\n# For development (bind mount source code)\ndocker run -d -v $(pwd)\u002Fsrc:\u002Fapp\u002Fsrc -p 3000:3000 --name dev my-app\n\n# Interactive debugging (auto-remove on exit)\ndocker run -it --rm ubuntu:22.04 \u002Fbin\u002Fbash\n\n# With resource limits and restart policy\ndocker run -d --memory=512m --cpus=1.5 --restart=unless-stopped --name app my-app\n```\n\nKey flags: `-d` detached, `-it` interactive+tty, `--rm` auto-remove, `-p` port (host:container), `-e` env var, `-v` volume, `--name` name, `--restart` restart policy.\n\n**Manage running containers:**\n\n```bash\ndocker ps                        # running containers\ndocker ps -a                     # all (including stopped)\ndocker stop NAME                 # graceful stop\ndocker start NAME                # start stopped container\ndocker restart NAME              # stop + start\ndocker rm NAME                   # remove stopped container\ndocker rm -f NAME                # force remove running container\ndocker container prune           # remove ALL stopped containers\n```\n\n**Interact with containers:**\n\n```bash\ndocker exec -it NAME \u002Fbin\u002Fsh          # shell access (use \u002Fbin\u002Fbash if available)\ndocker exec NAME env                   # view environment variables\ndocker exec -u root NAME apt update    # run as specific user\ndocker logs --tail 100 -f NAME         # follow last 100 lines\ndocker logs --since 2h NAME            # logs from last 2 hours\ndocker cp NAME:\u002Fpath\u002Ffile .\u002Flocal      # copy file from container\ndocker cp .\u002Ffile NAME:\u002Fpath\u002F           # copy file to container\ndocker inspect NAME                    # full container details (JSON)\ndocker stats --no-stream               # resource usage snapshot\ndocker top NAME                        # running processes\n```\n\n### 3. Image management\n\n```bash\n# Build\ndocker build -t my-app:latest .\ndocker build -t my-app:prod -f Dockerfile.prod .\ndocker build --no-cache -t my-app .              # clean rebuild\nDOCKER_BUILDKIT=1 docker build -t my-app .       # faster with BuildKit\n\n# Pull and push\ndocker pull node:20-alpine\ndocker login ghcr.io\ndocker tag my-app:latest registry\u002Fmy-app:v1.0\ndocker push registry\u002Fmy-app:v1.0\n\n# Inspect\ndocker images                          # list local images\ndocker history IMAGE                   # see layers\ndocker inspect IMAGE                   # full details\n\n# Cleanup\ndocker image prune                     # remove dangling (untagged) images\ndocker image prune -a                  # remove ALL unused images (careful!)\ndocker image prune -a --filter \"until=168h\"   # unused images older than 7 days\n```\n\n### 4. Docker Compose\n\n```bash\n# Start\u002Fstop\n# PITFALL: Do not run `docker compose up -d` directly in the foreground terminal. It starts background daemon processes which the terminal tool rejects as \"hanging\". \n# ALWAYS use: terminal(command=\"cd \u002Fpath && docker compose up -d\", background=true, notify_on_complete=true)\n# Note: Sometimes `docker-compose` is not found, always try `docker compose` as a fallback.\ndocker compose up -d                   # start all services detached\ndocker compose up -d --build           # rebuild images before starting\ndocker compose down                    # stop and remove containers\ndocker compose down -v                 # also remove volumes (DESTROYS DATA)\n```\n\n# Monitoring\ndocker compose ps                      # list services\ndocker compose logs -f api             # follow logs for specific service\ndocker compose logs --tail 50          # last 50 lines all services\n\n# Interaction\ndocker compose exec api \u002Fbin\u002Fsh        # shell into running service\ndocker compose run --rm api npm test   # one-off command (new container)\ndocker compose restart api             # restart specific service\n\n# Validation\ndocker compose config                  # validate and view resolved config\n```\n\n**Minimal compose.yml example:**\n\n```yaml\nservices:\n  api:\n    build: .\n    ports:\n      - \"3000:3000\"\n    environment:\n      - DATABASE_URL=postgres:\u002F\u002Fuser:pass@db:5432\u002Fmydb\n    depends_on:\n      db:\n        condition: service_healthy\n\n  db:\n    image: postgres:16-alpine\n    environment:\n      POSTGRES_USER: user\n      POSTGRES_PASSWORD: pass\n      POSTGRES_DB: mydb\n    volumes:\n      - pgdata:\u002Fvar\u002Flib\u002Fpostgresql\u002Fdata\n    healthcheck:\n      test: [\"CMD-SHELL\", \"pg_isready -U user\"]\n      interval: 10s\n      timeout: 5s\n      retries: 5\n\nvolumes:\n  pgdata:\n```\n\n### 5. Volumes and networks\n\n```bash\n# Volumes\ndocker volume ls                       # list volumes\ndocker volume create mydata            # create named volume\ndocker volume inspect mydata           # details (mount point, etc.)\ndocker volume rm mydata                # remove (fails if in use)\ndocker volume prune                    # remove unused volumes\n\n# Networks\ndocker network ls                      # list networks\ndocker network create mynet            # create bridge network\ndocker network inspect mynet           # details (connected containers)\ndocker network connect mynet NAME      # attach container to network\ndocker network disconnect mynet NAME   # detach container\ndocker network rm mynet                # remove network\ndocker network prune                   # remove unused networks\n```\n\n### 6. Common Build and Runtime Pitfalls\n\n- **Build Resources (No space left on device):** Production builds (like Next.js `npm run build` inside a Dockerfile) consume significant RAM and disk space. In constrained environments, this often causes `no space left on device` errors during `docker compose build`. Clean up space aggressively (`docker system prune -af --volumes`) before retrying the build.\n- **Port Conflicts:** When running containers via `docker-compose` or `docker run`, map a free port (e.g., `3001:3000` or `5433:5432`) if the host's target port is occupied by another local service, otherwise the container will fail to start with a `Bind for 0.0.0.0:XXXX failed: port is already allocated` error.\n- **Dependency Resolution in Build:** When a `pip install` step in a Dockerfile fails due to `ResolutionImpossible`, loosen strict version pins (e.g., change `==` to `>=`) in the `requirements.txt` to allow the package manager to resolve shared underlying dependencies.\n\n## Best Practices\n\n### Security: Strict Port Binding\n**Pitfall:** Defining ports as `- \"5432:5432\"` in `docker-compose.yml` binds to `0.0.0.0` by default, exposing the service (e.g., PostgreSQL, Redis) to the public internet. This leads directly to automated brute-force attacks and malware infections.\n**Fix:** If a port must be accessible from the host but NOT the public internet, bind it strictly to `127.0.0.1`:\n```yaml\nports:\n  - \"127.0.0.1:5432:5432\"\n```\nIf it only needs to be accessible to other containers (e.g., via Traefik or a Docker network), remove the `ports:` block entirely.\n\n## Troubleshooting Common Errors\n\nAlways start with a diagnostic before cleaning:\n\n```bash\n# Check what's using space\ndocker system df                       # summary\ndocker system df -v                    # detailed breakdown\n\n# Targeted cleanup (safe)\ndocker container prune                 # stopped containers\ndocker image prune                     # dangling images\ndocker volume prune                    # unused volumes\ndocker network prune                   # unused networks\n\n# Aggressive cleanup (confirm with user first!)\ndocker system prune                    # containers + images + networks\ndocker system prune -a                 # also unused images\ndocker system prune -a --volumes       # EVERYTHING — named volumes too\n```\n\n**Warning:** Never run `docker system prune -a --volumes` without confirming with the user. This removes named volumes with potentially important data.\n\n## Pitfalls\n- **No Space Left on Device**: Docker builds (like `next build` or heavy `pip install` phases) can fail with `write ... no space left on device` on VPS instances with limited disk space. Run `docker system prune -af --volumes` to reclaim space before retrying the build.\n- **Port Allocation Failures**: If starting a container fails with `Bind for 0.0.0.0:XXXX failed: port is already allocated`, edit the compose file to map to a free host port (e.g., change `\"4200:4200\"` to `\"4202:4200\"`).\n- **Host Volume Permissions**: When mounting host directories (e.g., for Next.js), the container user might not have write access, causing `EACCES` during build\u002Frun. Fix it by running an alpine container temporarily to adjust permissions: `docker run --rm -v $(pwd):\u002Fapp alpine chown -R 1000:1000 \u002Fapp\u002F\u003Cdir>`.\n- **Container-to-Host `localhost` Routing**: `localhost`\u002F`127.0.0.1` inside a container points to the container itself, not the host. If a host process (proxy, local API, dev server) must be reached from a container, `curl http:\u002F\u002Flocalhost:PORT` will fail with `Connection refused`. Fix: use the Docker bridge IP of the host interface on the same network, typically `ip route show table local` or `ip addr show` to find the bridge IP (e.g., `10.0.2.1`), then expose that host port to the container via compose `environment:` rather than hardcoding IPs in application code. Prefer an env var like `HOST_GATEWAY`\u002F`AI_PROXY_URL` so the same image works both locally and in Docker.\n- **Malware in RAM (Postgres\u002FRedis exploits):** If the VPS runs out of RAM and you spot a suspicious process (like `\u002Ftmp\u002Fpostgresql` running under an unknown user like `70`) consuming massive memory, it is likely a cryptominer exploiting weak container credentials or open ports (e.g., exposed PostgreSQL without a password). These malware variants often delete their own binaries from `\u002Ftmp` and run entirely in memory. To fix: the agent will NOT be able to kill it via `sudo` due to password blocks. Advise the user to SSH in and manually run `sudo kill -9 \u003CPID>`, followed by `sudo reboot` to clear the RAM. Alternatively, if the user explicitly provides their root password, you can execute the kill command via `export SUDO_ASKPASS=\u002Ftmp\u002Fap.sh` using a temporary executable script that echoes the password. After reboot or kill, review Docker container port bindings (e.g., bind DB ports to `127.0.0.1:5432:5432` rather than `0.0.0.0` in `docker-compose.yml`), strengthen passwords, and ensure the host firewall (UFW) is active and blocking external database access.\n| Problem | Cause | Fix |\n|---------|-------|-----|\n| Container-to-host service `Connection refused` | App inside Docker uses `localhost:PORT` but service runs on host | Use env var + Docker bridge IP in compose; see `cli-proxy-api-troubleshooting` skill references for pattern |\n| Container exits immediately | Main process finished or crashed | Check `docker logs NAME`, try `docker run -it --entrypoint \u002Fbin\u002Fsh IMAGE` |\n| \"docker-compose: command not found\" | Legacy docker-compose standalone binary is missing | Use the modern Compose plugin via `docker compose` instead |\n| \"port is already allocated\" | Another process using that port | `docker ps` or `lsof -i :PORT` to find it |\n| \"no space left on device\" | Docker disk full | `docker system df` then targeted prune |\n| Can't connect to container | App binds to 127.0.0.1 inside container | App must bind to `0.0.0.0`, check `-p` mapping |\n| Permission denied on volume | UID\u002FGID mismatch host vs container | Use `--user $(id -u):$(id -g)` or fix permissions |\n| Compose services can't reach each other | Wrong network or service name | Services use service name as hostname, check `docker compose config` |\n| Build cache not working | Layer order wrong in Dockerfile | Put rarely-changing layers first (deps before source code) |\n| Image too large | No multi-stage build, no .dockerignore | Use multi-stage builds, add `.dockerignore` |\n| Client version is too old | Modern Docker Engine (29.4+) raised MinAPIVersion to 1.40 | SDKs (like Traefik's) negotiating with \u003C1.40 will fail. Workaround: deploy a TCP relay (e.g., `traefik-docker29-fix`) to rewrite the API version in flight. |\n\n## Verification\n\nAfter any Docker operation, verify the result:\n\n- **Container started?** → `docker ps` (check status is \"Up\")\n- **Logs clean?** → `docker logs --tail 20 NAME` (no errors)\n- **Port accessible?** → `curl -s http:\u002F\u002Flocalhost:PORT` or `docker port NAME`\n- **Volume mounted?** → `docker inspect -f '{{ .Mounts }}' NAME`\n- **Network connected?** → `docker network inspect NAME`\n- **Disk freed?** → `docker system df` (compare before\u002Fafter)\n\n## Security Pitfalls\n- **Exposed Database Ports:** Never map database ports (e.g., `5432:5432`) to `0.0.0.0` on a public VPS. This exposes the database to the internet, inviting brute-force attacks and malware injections (e.g., cryptominers installed via OS command execution vulnerabilities). **Always bind to localhost** (e.g., `127.0.0.1:5432:5432`) unless explicit public access is required and secured by a firewall.\n- **Unrestricted Firewall:** Relying solely on Docker's port mapping without a host firewall (like UFW) is dangerous. Enable UFW, set default incoming to `deny`, and explicitly `allow` only required ports (22, 80, 443).\n\n## Dockerfile Optimization Tips\n\nWhen reviewing or creating a Dockerfile, suggest these improvements:\n\n1. **Multi-stage builds** — separate build environment from runtime to reduce final image size\n2. **Layer ordering** — put dependencies before source code so changes don't invalidate cached layers\n3. **Combine RUN commands** — fewer layers, smaller image\n4. **Use .dockerignore** — exclude `node_modules`, `.git`, `__pycache__`, etc.\n5. **Pin base image versions** — `node:20-alpine` not `node:latest`\n6. **Run as non-root** — add `USER` instruction for security\n7. **Use slim\u002Falpine bases** — `python:3.12-slim` not `python:3.12`\n8. **Port Security (Zero-Trust)** — Never expose database ports (e.g., PostgreSQL `5432`, Redis `6379`) or internal services to `0.0.0.0` unless explicitly required and secured by external firewalls. Always bind to localhost (`127.0.0.1:\u003Cport>:\u003Cport>`) for services placed behind a reverse proxy (like Traefik) to prevent brute-force attacks and malware\u002Fcryptominer infections.\n","# Docker Management\n\nManage Docker containers, images, volumes, networks, and Compose stacks using standard Docker CLI commands. No additional dependencies beyond Docker itself.\n\n## When to Use\n\n- Run, stop, restart, remove, or inspect containers\n- Build, pull, push, tag, or clean up Docker images\n- Work with Docker Compose (multi-service stacks)\n- Manage volumes or networks\n- Debug a crashing container or analyze logs\n- Check Docker disk usage or free up space\n- Review or optimize a Dockerfile\n\n## Prerequisites\n\n- Docker Engine installed and running\n- User added to the `docker` group (or use `sudo`)\n- Docker Compose v2 (included with modern Docker installations)\n\nQuick check:\n\n```bash\ndocker --version && docker compose version\n```\n\n- `references\u002Fpostgres-miner-sudo-askpass.md` — Handling memory-resident PostgreSQL cryptominers when the user provides a password using the `SUDO_ASKPASS` technique.\n- `references\u002Fmemory-resident-malware-removal.md` — General workflow for identifying and removing memory-resident cryptominers.\n\n\n| Task | Command |\n|------|---------|\n| Run container (background) | `docker run -d --name NAME IMAGE` |\n| Stop + remove | `docker stop NAME && docker rm NAME` |\n| View logs (follow) | `docker logs --tail 50 -f NAME` |\n| Shell into container | `docker exec -it NAME \u002Fbin\u002Fsh` |\n| List all containers | `docker ps -a` |\n| Build image | `docker build -t TAG .` |\n| Compose up | `docker compose up -d` |\n| Compose down | `docker compose down` |\n| Disk usage | `docker system df` |\n| Cleanup dangling | `docker image prune && docker container prune` |\n\n## Procedure\n\n### 1. Identify the domain\n\nFigure out which area the request falls into:\n\n- **Container lifecycle** → run, stop, start, restart, rm, pause\u002Funpause\n- **Container interaction** → exec, cp, logs, inspect, stats\n- **Image management** → build, pull, push, tag, rmi, save\u002Fload\n- **Docker Compose** → up, down, ps, logs, exec, build, config\n- **Volumes & networks** → create, inspect, rm, prune, connect\n- **Troubleshooting** → log analysis, exit codes, resource issues\n\n### 2. Container operations\n\n**Restart Policies (Ensuring Resilience):**\nWhen deploying critical infrastructure (databases, proxies, APIs), ALWAYS set the restart policy to `unless-stopped`. This ensures they spin back up automatically after a VPS reboot (check reboot via `uptime`).\n```bash\n# Update existing exited\u002Frunning containers to auto-restart\ndocker update --restart unless-stopped \u003Ccontainer1> \u003Ccontainer2>\n```\n\n**Run a new container:**\n\n```bash\n# Detached service with port mapping\ndocker run -d --name web -p 8080:80 nginx\n\n# With environment variables\ndocker run -d -e POSTGRES_PASSWORD=secret -e POSTGRES_DB=mydb --name db postgres:16\n\n# With persistent data (named volume)\ndocker run -d -v pgdata:\u002Fvar\u002Flib\u002Fpostgresql\u002Fdata --name db postgres:16\n\n# For development (bind mount source code)\ndocker run -d -v $(pwd)\u002Fsrc:\u002Fapp\u002Fsrc -p 3000:3000 --name dev my-app\n\n# Interactive debugging (auto-remove on exit)\ndocker run -it --rm ubuntu:22.04 \u002Fbin\u002Fbash\n\n# With resource limits and restart policy\ndocker run -d --memory=512m --cpus=1.5 --restart=unless-stopped --name app my-app\n```\n\nKey flags: `-d` detached, `-it` interactive+tty, `--rm` auto-remove, `-p` port (host:container), `-e` env var, `-v` volume, `--name` name, `--restart` restart policy.\n\n**Manage running containers:**\n\n```bash\ndocker ps                        # running containers\ndocker ps -a                     # all (including stopped)\ndocker stop NAME                 # graceful stop\ndocker start NAME                # start stopped container\ndocker restart NAME              # stop + start\ndocker rm NAME                   # remove stopped container\ndocker rm -f NAME                # force remove running container\ndocker container prune           # remove ALL stopped containers\n```\n\n**Interact with containers:**\n\n```bash\ndocker exec -it NAME \u002Fbin\u002Fsh          # shell access (use \u002Fbin\u002Fbash if available)\ndocker exec NAME env                   # view environment variables\ndocker exec -u root NAME apt update    # run as specific user\ndocker logs --tail 100 -f NAME         # follow last 100 lines\ndocker logs --since 2h NAME            # logs from last 2 hours\ndocker cp NAME:\u002Fpath\u002Ffile .\u002Flocal      # copy file from container\ndocker cp .\u002Ffile NAME:\u002Fpath\u002F           # copy file to container\ndocker inspect NAME                    # full container details (JSON)\ndocker stats --no-stream               # resource usage snapshot\ndocker top NAME                        # running processes\n```\n\n### 3. Image management\n\n```bash\n# Build\ndocker build -t my-app:latest .\ndocker build -t my-app:prod -f Dockerfile.prod .\ndocker build --no-cache -t my-app .              # clean rebuild\nDOCKER_BUILDKIT=1 docker build -t my-app .       # faster with BuildKit\n\n# Pull and push\ndocker pull node:20-alpine\ndocker login ghcr.io\ndocker tag my-app:latest registry\u002Fmy-app:v1.0\ndocker push registry\u002Fmy-app:v1.0\n\n# Inspect\ndocker images                          # list local images\ndocker history IMAGE                   # see layers\ndocker inspect IMAGE                   # full details\n\n# Cleanup\ndocker image prune                     # remove dangling (untagged) images\ndocker image prune -a                  # remove ALL unused images (careful!)\ndocker image prune -a --filter \"until=168h\"   # unused images older than 7 days\n```\n\n### 4. Docker Compose\n\n```bash\n# Start\u002Fstop\n# PITFALL: Do not run `docker compose up -d` directly in the foreground terminal. It starts background daemon processes which the terminal tool rejects as \"hanging\". \n# ALWAYS use: terminal(command=\"cd \u002Fpath && docker compose up -d\", background=true, notify_on_complete=true)\n# Note: Sometimes `docker-compose` is not found, always try `docker compose` as a fallback.\ndocker compose up -d                   # start all services detached\ndocker compose up -d --build           # rebuild images before starting\ndocker compose down                    # stop and remove containers\ndocker compose down -v                 # also remove volumes (DESTROYS DATA)\n```\n\n# Monitoring\ndocker compose ps                      # list services\ndocker compose logs -f api             # follow logs for specific service\ndocker compose logs --tail 50          # last 50 lines all services\n\n# Interaction\ndocker compose exec api \u002Fbin\u002Fsh        # shell into running service\ndocker compose run --rm api npm test   # one-off command (new container)\ndocker compose restart api             # restart specific service\n\n# Validation\ndocker compose config                  # validate and view resolved config\n```\n\n**Minimal compose.yml example:**\n\n```yaml\nservices:\n  api:\n    build: .\n    ports:\n      - \"3000:3000\"\n    environment:\n      - DATABASE_URL=postgres:\u002F\u002Fuser:pass@db:5432\u002Fmydb\n    depends_on:\n      db:\n        condition: service_healthy\n\n  db:\n    image: postgres:16-alpine\n    environment:\n      POSTGRES_USER: user\n      POSTGRES_PASSWORD: pass\n      POSTGRES_DB: mydb\n    volumes:\n      - pgdata:\u002Fvar\u002Flib\u002Fpostgresql\u002Fdata\n    healthcheck:\n      test: [\"CMD-SHELL\", \"pg_isready -U user\"]\n      interval: 10s\n      timeout: 5s\n      retries: 5\n\nvolumes:\n  pgdata:\n```\n\n### 5. Volumes and networks\n\n```bash\n# Volumes\ndocker volume ls                       # list volumes\ndocker volume create mydata            # create named volume\ndocker volume inspect mydata           # details (mount point, etc.)\ndocker volume rm mydata                # remove (fails if in use)\ndocker volume prune                    # remove unused volumes\n\n# Networks\ndocker network ls                      # list networks\ndocker network create mynet            # create bridge network\ndocker network inspect mynet           # details (connected containers)\ndocker network connect mynet NAME      # attach container to network\ndocker network disconnect mynet NAME   # detach container\ndocker network rm mynet                # remove network\ndocker network prune                   # remove unused networks\n```\n\n### 6. Common Build and Runtime Pitfalls\n\n- **Build Resources (No space left on device):** Production builds (like Next.js `npm run build` inside a Dockerfile) consume significant RAM and disk space. In constrained environments, this often causes `no space left on device` errors during `docker compose build`. Clean up space aggressively (`docker system prune -af --volumes`) before retrying the build.\n- **Port Conflicts:** When running containers via `docker-compose` or `docker run`, map a free port (e.g., `3001:3000` or `5433:5432`) if the host's target port is occupied by another local service, otherwise the container will fail to start with a `Bind for 0.0.0.0:XXXX failed: port is already allocated` error.\n- **Dependency Resolution in Build:** When a `pip install` step in a Dockerfile fails due to `ResolutionImpossible`, loosen strict version pins (e.g., change `==` to `>=`) in the `requirements.txt` to allow the package manager to resolve shared underlying dependencies.\n\n## Best Practices\n\n### Security: Strict Port Binding\n**Pitfall:** Defining ports as `- \"5432:5432\"` in `docker-compose.yml` binds to `0.0.0.0` by default, exposing the service (e.g., PostgreSQL, Redis) to the public internet. This leads directly to automated brute-force attacks and malware infections.\n**Fix:** If a port must be accessible from the host but NOT the public internet, bind it strictly to `127.0.0.1`:\n```yaml\nports:\n  - \"127.0.0.1:5432:5432\"\n```\nIf it only needs to be accessible to other containers (e.g., via Traefik or a Docker network), remove the `ports:` block entirely.\n\n## Troubleshooting Common Errors\n\nAlways start with a diagnostic before cleaning:\n\n```bash\n# Check what's using space\ndocker system df                       # summary\ndocker system df -v                    # detailed breakdown\n\n# Targeted cleanup (safe)\ndocker container prune                 # stopped containers\ndocker image prune                     # dangling images\ndocker volume prune                    # unused volumes\ndocker network prune                   # unused networks\n\n# Aggressive cleanup (confirm with user first!)\ndocker system prune                    # containers + images + networks\ndocker system prune -a                 # also unused images\ndocker system prune -a --volumes       # EVERYTHING — named volumes too\n```\n\n**Warning:** Never run `docker system prune -a --volumes` without confirming with the user. This removes named volumes with potentially important data.\n\n## Pitfalls\n- **No Space Left on Device**: Docker builds (like `next build` or heavy `pip install` phases) can fail with `write ... no space left on device` on VPS instances with limited disk space. Run `docker system prune -af --volumes` to reclaim space before retrying the build.\n- **Port Allocation Failures**: If starting a container fails with `Bind for 0.0.0.0:XXXX failed: port is already allocated`, edit the compose file to map to a free host port (e.g., change `\"4200:4200\"` to `\"4202:4200\"`).\n- **Host Volume Permissions**: When mounting host directories (e.g., for Next.js), the container user might not have write access, causing `EACCES` during build\u002Frun. Fix it by running an alpine container temporarily to adjust permissions: `docker run --rm -v $(pwd):\u002Fapp alpine chown -R 1000:1000 \u002Fapp\u002F\u003Cdir>`.\n- **Container-to-Host `localhost` Routing**: `localhost`\u002F`127.0.0.1` inside a container points to the container itself, not the host. If a host process (proxy, local API, dev server) must be reached from a container, `curl http:\u002F\u002Flocalhost:PORT` will fail with `Connection refused`. Fix: use the Docker bridge IP of the host interface on the same network, typically `ip route show table local` or `ip addr show` to find the bridge IP (e.g., `10.0.2.1`), then expose that host port to the container via compose `environment:` rather than hardcoding IPs in application code. Prefer an env var like `HOST_GATEWAY`\u002F`AI_PROXY_URL` so the same image works both locally and in Docker.\n- **Malware in RAM (Postgres\u002FRedis exploits):** If the VPS runs out of RAM and you spot a suspicious process (like `\u002Ftmp\u002Fpostgresql` running under an unknown user like `70`) consuming massive memory, it is likely a cryptominer exploiting weak container credentials or open ports (e.g., exposed PostgreSQL without a password). These malware variants often delete their own binaries from `\u002Ftmp` and run entirely in memory. To fix: the agent will NOT be able to kill it via `sudo` due to password blocks. Advise the user to SSH in and manually run `sudo kill -9 \u003CPID>`, followed by `sudo reboot` to clear the RAM. Alternatively, if the user explicitly provides their root password, you can execute the kill command via `export SUDO_ASKPASS=\u002Ftmp\u002Fap.sh` using a temporary executable script that echoes the password. After reboot or kill, review Docker container port bindings (e.g., bind DB ports to `127.0.0.1:5432:5432` rather than `0.0.0.0` in `docker-compose.yml`), strengthen passwords, and ensure the host firewall (UFW) is active and blocking external database access.\n| Problem | Cause | Fix |\n|---------|-------|-----|\n| Container-to-host service `Connection refused` | App inside Docker uses `localhost:PORT` but service runs on host | Use env var + Docker bridge IP in compose; see `cli-proxy-api-troubleshooting` skill references for pattern |\n| Container exits immediately | Main process finished or crashed | Check `docker logs NAME`, try `docker run -it --entrypoint \u002Fbin\u002Fsh IMAGE` |\n| \"docker-compose: command not found\" | Legacy docker-compose standalone binary is missing | Use the modern Compose plugin via `docker compose` instead |\n| \"port is already allocated\" | Another process using that port | `docker ps` or `lsof -i :PORT` to find it |\n| \"no space left on device\" | Docker disk full | `docker system df` then targeted prune |\n| Can't connect to container | App binds to 127.0.0.1 inside container | App must bind to `0.0.0.0`, check `-p` mapping |\n| Permission denied on volume | UID\u002FGID mismatch host vs container | Use `--user $(id -u):$(id -g)` or fix permissions |\n| Compose services can't reach each other | Wrong network or service name | Services use service name as hostname, check `docker compose config` |\n| Build cache not working | Layer order wrong in Dockerfile | Put rarely-changing layers first (deps before source code) |\n| Image too large | No multi-stage build, no .dockerignore | Use multi-stage builds, add `.dockerignore` |\n| Client version is too old | Modern Docker Engine (29.4+) raised MinAPIVersion to 1.40 | SDKs (like Traefik's) negotiating with \u003C1.40 will fail. Workaround: deploy a TCP relay (e.g., `traefik-docker29-fix`) to rewrite the API version in flight. |\n\n## Verification\n\nAfter any Docker operation, verify the result:\n\n- **Container started?** → `docker ps` (check status is \"Up\")\n- **Logs clean?** → `docker logs --tail 20 NAME` (no errors)\n- **Port accessible?** → `curl -s http:\u002F\u002Flocalhost:PORT` or `docker port NAME`\n- **Volume mounted?** → `docker inspect -f '{{ .Mounts }}' NAME`\n- **Network connected?** → `docker network inspect NAME`\n- **Disk freed?** → `docker system df` (compare before\u002Fafter)\n\n## Security Pitfalls\n- **Exposed Database Ports:** Never map database ports (e.g., `5432:5432`) to `0.0.0.0` on a public VPS. This exposes the database to the internet, inviting brute-force attacks and malware injections (e.g., cryptominers installed via OS command execution vulnerabilities). **Always bind to localhost** (e.g., `127.0.0.1:5432:5432`) unless explicit public access is required and secured by a firewall.\n- **Unrestricted Firewall:** Relying solely on Docker's port mapping without a host firewall (like UFW) is dangerous. Enable UFW, set default incoming to `deny`, and explicitly `allow` only required ports (22, 80, 443).\n\n## Dockerfile Optimization Tips\n\nWhen reviewing or creating a Dockerfile, suggest these improvements:\n\n1. **Multi-stage builds** — separate build environment from runtime to reduce final image size\n2. **Layer ordering** — put dependencies before source code so changes don't invalidate cached layers\n3. **Combine RUN commands** — fewer layers, smaller image\n4. **Use .dockerignore** — exclude `node_modules`, `.git`, `__pycache__`, etc.\n5. **Pin base image versions** — `node:20-alpine` not `node:latest`\n6. **Run as non-root** — add `USER` instruction for security\n7. **Use slim\u002Falpine bases** — `python:3.12-slim` not `python:3.12`\n8. **Port Security (Zero-Trust)** — Never expose database ports (e.g., PostgreSQL `5432`, Redis `6379`) or internal services to `0.0.0.0` unless explicitly required and secured by external firewalls. Always bind to localhost (`127.0.0.1:\u003Cport>:\u003Cport>`) for services placed behind a reverse proxy (like Traefik) to prevent brute-force attacks and malware\u002Fcryptominer infections.\n",{"name":5,"author":24,"license":15,"version":25,"metadata":26,"platforms":40,"description":7},"sprmn24","1.0.0",{"hermes":27},{"tags":28,"category":31,"requires_toolsets":38},[29,30,31,32,33,34,35,36,37],"docker","containers","devops","infrastructure","compose","images","volumes","networks","debugging",[39],"terminal",[41,42,43],"linux","macos","windows","main","236825fbf4e5956a8cd2b0bf843494f0a5dfaf04","skills\u002Fdevops\u002Fdocker-management","https:\u002F\u002Fgithub.com\u002FSatangThevalue\u002Fai-skills","https:\u002F\u002Fgithub.com\u002FSatangThevalue","https:\u002F\u002Fwww.linkedin.com\u002Fin\u002Fsatangthevalue\u002F","Hi, I'm Sa-Tang. 🖐️🖐️🖐️\r\nThanks for following.\r\nสวัสดีครับ สตังค์ครับผม\r\nขอบคุณหรับการติดตามครับ","2026-10-10 12:10:40",{"source":8,"skillName":5,"commands":53,"prompt":63,"zipAvailable":64},[54,57,60],{"tool":55,"command":56},"npx","npx skills add SatangThevalue\u002Fai-skills --skill docker-management",{"tool":58,"command":59},"bunx","bunx skills add SatangThevalue\u002Fai-skills --skill docker-management",{"tool":61,"command":62},"pnpm","pnpm dlx skills add SatangThevalue\u002Fai-skills --skill docker-management","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FSatangThevalue\u002Fai-skills\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fdocker-management\u002FSKILL.md",true,[66,72,76,80],{"path":67,"resourceType":68,"resourceTypeDesc":69,"sizeBytes":70,"sourceHtmlUrl":71},"references\u002Fmemory-resident-malware-removal.md","REFERENCE","参考文档",2885,"https:\u002F\u002Fgithub.com\u002FSatangThevalue\u002Fai-skills\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fdocker-management\u002Freferences\u002Fmemory-resident-malware-removal.md",{"path":73,"resourceType":68,"resourceTypeDesc":69,"sizeBytes":74,"sourceHtmlUrl":75},"references\u002Fpnpm-ci-tty-error.md",867,"https:\u002F\u002Fgithub.com\u002FSatangThevalue\u002Fai-skills\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fdocker-management\u002Freferences\u002Fpnpm-ci-tty-error.md",{"path":77,"resourceType":68,"resourceTypeDesc":69,"sizeBytes":78,"sourceHtmlUrl":79},"references\u002Fpostgres-miner-incident.md",1219,"https:\u002F\u002Fgithub.com\u002FSatangThevalue\u002Fai-skills\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fdocker-management\u002Freferences\u002Fpostgres-miner-incident.md",{"path":81,"resourceType":68,"resourceTypeDesc":69,"sizeBytes":82,"sourceHtmlUrl":83},"references\u002Fpostgres-miner-sudo-askpass.md",1665,"https:\u002F\u002Fgithub.com\u002FSatangThevalue\u002Fai-skills\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fdocker-management\u002Freferences\u002Fpostgres-miner-sudo-askpass.md",[85,92,99,106,113,120],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":19},"01M76TQY0W54NCMRVE9HB8MMTA","writing-plans","Write implementation plans: bite-sized tasks, paths, code.","https:\u002F\u002Fgithub.com\u002FSatangThevalue\u002Fai-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsoftware-development\u002Fwriting-plans\u002FSKILL.md",[],[],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":19},"01M76TNN9AYY91KD4DT415K1FF","subagent-driven-development","Execute plans via delegate_task subagents (2-stage review).","https:\u002F\u002Fgithub.com\u002FSatangThevalue\u002Fai-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsoftware-development\u002Fsubagent-driven-development\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":19},"01M76TME6SXP9SYJZCXX5FFZHR","react-composition-2026","Teaches modern React composition patterns for 2025\u002F2026. Use when designing component APIs, building shared UI libraries, or refactoring prop-heavy components.","https:\u002F\u002Fgithub.com\u002FSatangThevalue\u002Fai-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsoftware-development\u002Freact-composition-2026\u002FSKILL.md",[],[],{"skillNo":107,"name":108,"nameZh":6,"description":109,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":110,"categories":111,"keywords":112,"publishedAt":19},"01M76TMAR2D5G9BKZWGEFJKWT2","react-2026","Provides a comprehensive guide to the modern React 2026 stack. Use when starting a new React project or modernizing an existing one with current frameworks, build tools, routing, state management, or AI integration.","https:\u002F\u002Fgithub.com\u002FSatangThevalue\u002Fai-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsoftware-development\u002Freact-2026\u002FSKILL.md",[],[],{"skillNo":114,"name":115,"nameZh":6,"description":116,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":117,"categories":118,"keywords":119,"publishedAt":19},"01M76TM2FA8ZFZR1S6ZM34WFFK","plan","Plan mode: write markdown plan to .hermes\u002Fplans\u002F, no exec.","https:\u002F\u002Fgithub.com\u002FSatangThevalue\u002Fai-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsoftware-development\u002Fplan\u002FSKILL.md",[],[],{"skillNo":121,"name":122,"nameZh":6,"description":123,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":124,"categories":125,"keywords":126,"publishedAt":19},"01M76TJVNAWDZ7DYQK3ZS0X09J","hermes-s6-container-supervision","Modify, debug, or extend the s6-overlay supervision tree inside the Hermes Agent Docker image — adding new services, debugging profile gateways, understanding the Architecture B main-program pattern.","https:\u002F\u002Fgithub.com\u002FSatangThevalue\u002Fai-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsoftware-development\u002Fhermes-s6-container-supervision\u002FSKILL.md",[],[]]